<?php

namespace Home\Controller;

use Common\Soap;
use Common\Top;
use Common\Utils;
use Common\Api_51;
use Common\Sms;

class WxJsAPIController extends CommonController {

    //测试在线支付
    public function ceshiwxpay() {
        //header('Access-Control-Allow-Origin:*');  
        $amount = I('wx_pay_amount');

        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \JsApi_pub();

        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        if (!isset($_GET['code'])) {
            //触发微信返回code码
            $url = $jsApi->createOauthUrlForCode(C('WxPayConf_pub.JS_API_CALL_URL'));
            $total_fee = $amount;
            $url = str_replace("STATE", $total_fee, $url);
            //dump($url);exit;
            Header("Location: $url");
        } else {
            //dump($_GET['code']);exit;
            //获取code码，以获取openid
            $code = $_GET['code'];
            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
        }

        $wx_pay_amount = I('state');

        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();

        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid", $openid); //商品描述
        $unifiedOrder->setParameter("body", "充值"); //商品描述
        //自定义订单号，此处仅作举例
        $timeStamp = time();
        $out_trade_no = C('WxPayConf_pub.APPID') . $timeStamp;
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no); //商户订单号
        $unifiedOrder->setParameter("total_fee", $wx_pay_amount); //总金额
        $unifiedOrder->setParameter("notify_url", C('WxPayConf_pub.NOTIFY_URL')); //通知地址
        $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);

        $jsApiParameters = $jsApi->getParameters();

        $this->assign('appId', $jsApiParameters['appId']);
        $this->assign('timeStamp', $jsApiParameters['timeStamp']);
        $this->assign('nonceStr', $jsApiParameters['nonceStr']);
        $this->assign('package', $jsApiParameters['package']);
        $this->assign('signType', $jsApiParameters['signType']);
        $this->assign('paySign', $jsApiParameters['paySign']);
        $this->display();
    }

    public function notify() {
        vendor('WxPayPubHelper.WxPayPubHelper');
        //使用通用通知接口
        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;

        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
//         $log_ = new Log_();
        $log_name = __ROOT__ . "/Public/notify_url.log"; //log文件路径

        log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");

        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
            } elseif ($notify->data["result_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
            } else {
                //此处应该更新一下订单状态，商户自行增删操作
                $notify->setReturnParameter("return_code","FAIL");
                log_result($log_name, "【支付成功】:\n" . $xml . "\n");
            }

            //商户自行增加处理流程,
            //例如：更新订单状态
            //例如：数据库操作
            //例如：推送支付完成信息
        }
    }

    //微信充值记录
    public function wx_recharge_record() {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $userList = $this->userInfo;

            $data['entity_type'] = Top::EntityTypeAgency; //实体类型4，顾问
            $data['operator_id'] = $userList['operator_id']; //所属运营商id
            $data['entity_id'] = $userList['id'];  //顾问id
            $data['entity_name'] = $userList['name']; //顾问姓名
            $data['state'] = Top::ApplyStateStayPay; //待审核状态
            $data['merchant_number'] = C('WxPayConf_pub.APPID') . time();
            $data['account'] = $userList['account']; //账户
            $data['create_time'] = date('Y-m-d H:i:s', time()); //申请充值时间
            $data['create_time'] = date('Y-m-d H:i:s', time()); //申请充值时间
            $data['amount'] = Utils::getFen(I('amount')); //充值钱转换*100
            $data['topup_type'] = I('on_topup_type'); //充值类型id
            $data['pay_state'] = 1; //线下支付

            $postCode = I('applyTopUp_code'); //判断用的码，简单的防止post恶意请求
            $code = session('applyTopUp');

            if ($postCode == $code) {
                $result = M('account_topup')->add($data);
                session('applyTopUp', null);
            }

            if ($result) {
                $datas['wx_order_id']= $result;
                $datas['merchant_number']= $data['merchant_number'];
                return $datas;
            } 
        }else{
             $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }

    public function personal() {
        $openId = I('get.openId');
        session('openid', $openId);
        $agencyOpenId = session('openid');
        $domain = $_SERVER["SERVER_NAME"];

        if (strpos($domain, '.demo.') !== false) {
            $url = 'http' . $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["SERVER_NAME"] . ":8080" . $_SERVER["REQUEST_URI"];
            $returnUrl = "http://" . $domain . ":8080/index.php/Home/Login/index";
            $queryUrl = "http://" . $domain . ":8080/index.php/Home/Login/wxLoginIndex";
        } else {
            $url = 'http' . $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            $returnUrl = "http://" . $domain . "/index.php/Home/Login/index";
            $queryUrl = "http://" . $domain . "/index.php/Home/Login/wxLoginIndex";
        }

        if (!empty($agencyOpenId)) {
            $agencyInfo = M('agency')->where("domain = '{$domain}' && weixinmp_openid = '{$agencyOpenId}'")->find();
            if (!empty($agencyInfo)) {
                $jsApi = new \JsApi_pub();
                $accessToken = $jsApi->getAccessToken();
                $visitorWxInfo = $jsApi->getAccessTokenOpenId($accessToken, $agencyOpenId);

                $data['subscribe'] = $visitorWxInfo['subscribe'];
                $data['nickname'] = preg_replace("/[^\x{4e00}-\x{9fa5}]/iu", '', $visitorWxInfo['nickname']);
                $data['nickname_base64'] = base64_encode($visitorWxInfo['nickname']);
                $data['sex'] = $visitorWxInfo['sex'];
                $data['language'] = $visitorWxInfo['language'];
                $data['city'] = $visitorWxInfo['city'];
                $data['province'] = $visitorWxInfo['province'];
                $data['country'] = $visitorWxInfo['country'];
                $data['headimgurl'] = $visitorWxInfo['headimgurl'];
                $data['subscribe_time'] = date("Y-m-d H:i:s", $visitorWxInfo['subscribe_time']);
                $data['remark'] = $visitorWxInfo['remark'];
                $data['groupid'] = $visitorWxInfo['groupid'];

                $agencyId = $agencyInfo['id'];
                M('agency')->where("id = '{$agencyId}'")->save($data);
            } else {
                $queryUrl = 'http://' . $domain . "/index.php/Home/WxJsAPI/myPlaneTicket";
            }
            Header("Location: $queryUrl");
            exit();
        } else {
            R('Oauth/getCode', array($url, $returnUrl));
        }
    }

    public function index() {
        $openId = I('get.openId');
        session('openid', $openId);
        $agencyOpenId = session('openid');

        $url = 'http' . $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        $domain = $_SERVER["SERVER_NAME"];

        $returnUrl = 'http://' . $domain . "/index.php/Home/Flight/flightQuery";

        if (!empty($agencyOpenId)) {
            $agencyInfo = M('agency')->where("domain = '{$domain}' && weixinmp_openid = '{$agencyOpenId}'")->find();

            if (!empty($agencyInfo)) {
                $queryUrl = 'http://' . $domain . "/index.php/Home/Flight/flightQuery";
            } else {
                $queryUrl = 'http://' . $domain . "/index.php/Home/WxJsAPI/flightQuery";
            }
            Header("Location: $queryUrl");
            exit();
        } else {
            R('Oauth/getCode', array($url, $returnUrl));
        }
    }

    /**
     * 初始化
     */
    public function _initialize() {
        vendor('WxPayPubHelper.WxPayPubHelper');
    }

    /**
     * 统一支付接口
     */
    public function jsApiCall() {
        $fid = I('get.fid');
        $orderFlightInfo = M('visitor_order_flight')->where("id = '{$fid}'")->find();

        //查询订单
        $flightPriceTotal = M('visitor_order_flight')->where("id = '{$fid}'")->field('id,price_total,sequence_no,org_jetquay,dst_jetquay')->find();

        $orgJetquay = $flightPriceTotal['org_jetquay'];
        $dstJetquay = $flightPriceTotal['dst_jetquay'];

        $flightOrderList = M("visitor_order_flight_detail")->where("order_flight_id = '{$fid}'")->select();
        $depCode = $flightOrderList[0]['dep_code'];
        $arrCode = $flightOrderList[0]['arr_code'];
        $flightNo = $flightOrderList[0]['flight_no'];
        $planeModel = $flightOrderList[0]['plane_model'];
        $depDate = $flightOrderList[0]['dep_date'];
        $depTime = $flightOrderList[0]['dep_time'];
        $arrTime = $flightOrderList[0]['arr_time'];
        $linkMan = $flightOrderList[0]['link_man'];
        $linkPhone = $flightOrderList[0]['link_phone'];
        $seatCode = $flightOrderList[0]['seat_class'];
        $priceTotal = Utils::getYuan($flightPriceTotal['price_total']);

        foreach ($flightOrderList as $k => $v) {
            $orderList[$k]['passenger_name'] = $v['passenger_name'];
            $orderList[$k]['passenger_type'] = $v['passenger_type'];
            $orderList[$k]['price_total'] = Utils::getYuan($v['par_price'] + $v['fuel_tax'] + $v['airport_tax']);
            $orderList[$k]['child_price_total'] = Utils::getYuan($v['par_price'] + $v['fuel_tax']);
            $orderList[$k]['par_price'] = Utils::getYuan($v['par_price']);
            $orderList[$k]['fuel_tax'] = Utils::getYuan($v['fuel_tax']);
            $orderList[$k]['airport_tax'] = Utils::getYuan($v['airport_tax']);
        }

        $openid = I('get.openid');
        $_SESSION['flightOrderCode'] = 400;

        $domain = I('get.redirectUrl');
        $redirectUrl = $domain . "/index.php/Home/WxJsAPI/myPlaneTicket";

        $this->assign('domain', $domain);
        $this->assign('redirectUrl', $redirectUrl);
        $this->assign('openid', $openid);
        $this->assign('orgJetquay', $orgJetquay);
        $this->assign('dstJetquay', $dstJetquay);
        $this->assign('priceTotal', $priceTotal);
        $this->assign('depCode', $depCode);
        $this->assign('arrCode', $arrCode);
        $this->assign('flightNo', $flightNo);
        $this->assign('planeModel', $planeModel);
        $this->assign('depDate', $depDate);
        $this->assign('depTime', $depTime);
        $this->assign('arrTime', $arrTime);
        $this->assign('linkMan', $linkMan);
        $this->assign('linkPhone', $linkPhone);
        $this->assign('orderList', $orderList);
        $this->assign('flightId', $fid);
        $this->assign('orderFlightInfo', $orderFlightInfo);
        $this->assign('seatCode', $seatCode);

        $operatorId = $orderFlightInfo['operator_id'];
        $operatorInfo = M('operator')->where("id = '{$operatorId}'")->find();
        $creditBalance = $operatorInfo['account_credit_balance'];

        $total = $flightPriceTotal['price_total'];
        $this->assign('creditBalance', $creditBalance);
        $this->assign('total', $total);

        if (IS_POST && IS_AJAX) {
            $fid = I('fid');
            $flightPriceTotal = M('visitor_order_flight')->where("id = '{$fid}'")->field('id,price_total,state')->find();
            //$state = $flightPriceTotal['state'];
//            if($state != Top::FlightOrderStateSubmitted){
//                $data['status'] = 2;
//                $this->ajaxReturn($data);
//            }
            //使用jsapi接口
            $jsApi = new \JsApi_pub();

            //=========步骤2：使用统一支付接口，获取prepay_id============
            //使用统一支付接口
            $unifiedOrder = new \UnifiedOrder_pub();
            //设置统一支付接口参数
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //spbill_create_ip已填,商户无需重复填写
            //sign已填,商户无需重复填写
            $openid = I('openid');
            $unifiedOrder->setParameter("openid", $openid); //商品描述
            $unifiedOrder->setParameter("body", "机票款"); //商品描述
            //自定义订单号，此处仅作举例
            //$timeStamp = time();
            // $out_trade_no = $timeStamp;
            //$unifiedOrder->setParameter("out_trade_no", $fid);//商户订单号
            //$unifiedOrder->setParameter("total_fee", 1);//总金额

            $totalFee = (int) $flightPriceTotal['price_total'];
            $unifiedOrder->setParameter("out_trade_no", $fid); //商户订单号
            $unifiedOrder->setParameter("total_fee", $totalFee); //总金额
            $unifiedOrder->setParameter("notify_url", "http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/jsApiNotify"); //通知地址
            $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
            //非必填参数，商户可根据实际情况选填
            //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
            $unifiedOrder->setParameter("device_info", "WEB"); //设备号
            //$unifiedOrder->setParameter("attach","XXXX");//附加数据
            //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
            //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
            //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
            //$unifiedOrder->setParameter("openid","XXXX");//用户标识
            //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
            //dump($unifiedOrder);exit();
            $prepay_id = $unifiedOrder->getPrepayId();
            //dump($prepay_id);
            //=========步骤3：使用jsapi调起支付============
            $jsApi->setPrepayId($prepay_id);

            $jsApiParameters = $jsApi->getParameters();

            $data['appId'] = $jsApiParameters['appId'];
            $data['timeStamp'] = $jsApiParameters['timeStamp'];
            $data['nonceStr'] = $jsApiParameters['nonceStr'];
            $data['package'] = $jsApiParameters['package'];
            $data['signType'] = $jsApiParameters['signType'];
            $data['paySign'] = $jsApiParameters['paySign'];
            $data['status'] = 1;

            $this->ajaxReturn($data);
        }

        $this->display();
    }

    /**
     * 异步通知方法
     */
    public function jsApiNotify() {
        $fileContent = file_get_contents('php://input');
        //转换为simplexml对象
        $content = "执行时间:" . date("Y-m-d H:i:s") . "\n";
        $d = date("Ymd", time());
        //$file = "./Public/notify_$d.log";
        $file = C('VISITOR_WXPAY_NOTIFY_PATH') . "/notify_$d.log";
        $fp = fopen($file, "a+");
        flock($fp, LOCK_EX);
        fwrite($fp, $content . $fileContent . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);

        $listAllData = $this->xml_to_array($fileContent);
        foreach ($listAllData as $k => $v) {
            $data[$k] = $v[0];
            $data['create_time'] = date("Y-m-d H:i:s", time());
        }

        $result = M('wxpay_notify')->add($data);

        $notifyInfo = M('wxpay_notify')->where("id = '{$result}'")->find();
        $returnCode = $notifyInfo['return_code'];
        $flightId = $notifyInfo['out_trade_no'];

        $flightDetailList = M('visitor_order_flight_detail')->where("order_flight_id = '{$flightId}'")->field('id,settle_price,fuel_tax,airport_tax,link_phone')->select();
        $mobile = $flightDetailList[0]['link_phone'];

        $priceTotal = 0;
        foreach ($flightDetailList as $k => $v) {
            $priceTotal += $v['settle_price'] + $v['fuel_tax'] + $v['airport_tax'];
        }

        $flightInfo = M('visitor_order_flight')->where("id = '{$flightId}'")->find();
        $operatorId = $flightInfo['operator_id'];
        $state = $flightInfo['state'];

        if ($returnCode == 'SUCCESS' && $state == Top::FlightOrderStateWaitingForPayment) {
            $paying['state'] = Top::FlightOrderStatePaying;
            M('visitor_order_flight')->where("id = '{$flightId}'")->save($paying);
            M('visitor_order_flight_detail')->where("order_flight_id = '{$flightId}'")->save($paying);

            $operatorResult = M('sys')->where("id = 1")->setDec('account_credit_balance', $priceTotal);

            $operatorList = M('sys')->where("id = 1")->find();
            $agencyData['operator_id'] = 0;
            $agencyData['action'] = '支出机票订单金额';
            $agencyData['entity_type'] = Top::EntityTypeSystem;
            $agencyData['entity_id'] = 1;
            $agencyData['account'] = $operatorList['account'];
            $agencyData['sn'] = Utils::getSn();
            //$agencyData['batch'] = $nowTime;
            $agencyData['amount'] = '-' . $priceTotal;
            $agencyData['balance'] = $operatorList['account_credit_balance'];
            $agencyData['create_time'] = date('Y-m-d H:i:s', time());
            $agencyData['remark'] = 'top_visitor_order_flight.id:' . $flightId;
            $agencyData['object_id'] = $flightId;
            $agencyData['object_type'] = Top::ObjectTypeFlight;
            $agencyData['object_name'] = '机票';
            $agencyDelmoney = M('flight_transaction')->add($agencyData);

            $orderFlightChildList = M('visitor_order_flight_detail')->where("order_flight_id = '{$flightId}' && passenger_type = 0")->select();
            if ($orderFlightChildList) {
                $url = $this->orderPayUrl();
                $data['agencyCode'] = $this->agencyCode();
                $data['orderNo'] = (string) $orderFlightChildList[0]['sequence_no'];                                         //提交订单后,得到的订单号
                $data['payType'] = '1';
                $data['payerLoginName'] = 'bjskt';                                    //默认平台登录号
                $sign = $this->agencyCode() . $data['orderNo'] . $data['payType'] . $data['payerLoginName'] . $this->sign();
                $data['sign'] = strtolower(MD5($sign));
                //返回 xml 格式
                $result = Utils::vpost($url, $data);
                $listAllData = $this->xml_to_array($result);
                $returnCode = $listAllData['returnCode'][0];

                //if ($returnCode == 'F') {
                //$data['msg'] = $listAllData['returnMessage'][0];
                //$data['status'] = 5;
                //$this->ajaxReturn($data);
                //}
            }
            $url = $this->orderPayUrl();
            $data['agencyCode'] = $this->agencyCode();
            $data['orderNo'] = $flightInfo['sequence_no'];                                         //提交订单后,得到的订单号
            $data['payType'] = '1';
            $data['payerLoginName'] = 'bjskt';                                    //默认平台登录号
            $sign = $this->agencyCode() . $data['orderNo'] . $data['payType'] . $data['payerLoginName'] . $this->sign();
            $data['sign'] = strtolower(MD5($sign));
            //返回 xml 格式
            $result = Utils::vpost($url, $data);
            $listAllData = $this->xml_to_array($result);
            $returnCode = $listAllData['returnCode'][0];

            //if ($returnCode == 'F') {
            //    $data['msg'] = $listAllData['returnMessage'][0];
            //    $data['status'] = 5;
            //    $this->ajaxReturn($data);
            //}

            $payed['state'] = Top::FlightOrderStatePayed;
            M('visitor_order_flight')->where("id = '{$flightId}'")->save($payed);
            M('visitor_order_flight_detail')->where("order_flight_id = '{$flightId}'")->save($payed);

            $orderNo = $flightInfo['sequence_no'];
            Sms::Send($mobile, "您已成功预定机票,订单号:" . $orderNo . ",出票结果将在几分钟后短信通知您", $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

            $notify = new \Notify_pub();
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
            $returnXml = $notify->returnXml();
            echo $returnXml;
        }
    }

    /**
     * 航班查询-页面
     */
    public function flightQuery() {
        $domain = $_SERVER['SERVER_NAME'];
        $domain = 'http://' . $domain . "/index.php/Home/WxJsAPI/flightQuery";
        $this->assign('domain', $domain);
        $this->display();
    }

    /**
     * 列表
     */
    public function flightQueryList() {
        if (IS_POST) {
            $url = $this->flightQueryUrl();
            $data['agencyCode'] = $this->agencyCode();
            $dayBefore = I('dayBefore');
            $dayAfter = I('dayAfter');

            $orgAirportCode = I('departure');
            if ($orgAirportCode == 'NAY') {
                $orgAirportCode = 'PEK';
            } else if ($orgAirportCode == 'PVG') {
                $orgAirportCode = 'SHA';
            } else {
                $orgAirportCode = I('departure');
            }

            $dstAirportCode = I('destination');
            if ($dstAirportCode == 'NAY') {
                $dstAirportCode = 'PEK';
            } else if ($dstAirportCode == 'PVG') {
                $dstAirportCode = 'SHA';
            } else {
                $dstAirportCode = I('destination');
            }

            if (!empty($dayBefore)) {
                $data['orgAirportCode'] = $orgAirportCode;
                $data['dstAirportCode'] = $dstAirportCode;

                $data['date'] = date('Y-m-d', strtotime("$dayBefore - 1 day"));
            } else if (!empty($dayAfter)) {
                $data['orgAirportCode'] = $orgAirportCode;
                $data['dstAirportCode'] = $dstAirportCode;

                $data['date'] = date('Y-m-d', strtotime("$dayAfter + 1 day"));
            } else {
                //出发地
                $departure = I('departure');
                $data['orgAirportCode'] = $this->airportname($departure);
                //目的地
                $destination = I('destination');
                $data['dstAirportCode'] = $this->airportname($destination);
                $data['date'] = I('timestart');
            }

            $data['onlyAvailableSeat'] = 0;
            $data['onlyNormalCommision'] = 0;
            $data['onlyOnWorkingCommision'] = 0;
            $data['onlySelfPNR'] = 0;

            $sign = $this->agencyCode() . $data['dstAirportCode'] . $data['onlyAvailableSeat'] . $data['onlyNormalCommision'] . $data['onlyOnWorkingCommision'] . $data['onlySelfPNR'] . $data['orgAirportCode'] . $this->sign();
            $data['sign'] = strtolower(MD5($sign));

            //返回 xml 格式
            $result = Utils::vpost($url, $data);
            //转换成数组
            $listAllData = $this->xml_to_array($result);
            //返回值
            $returnCode = $listAllData['returnCode'][0];

            if ($returnCode !== 'S') {
                $departure = I('departure');
                $destination = I('destination');
                $msg = '很抱歉，暂未查询到符合您要求的航班。您可以调整出行时间或目的地重新查询。';
                $this->assign('msg', $msg);
                $this->assign('departure', $departure);
                $this->assign('destination', $destination);
                $this->display("WxJsAPI/flightQueryError");
                exit();
            }

            //时间
            $date = $listAllData['flightItems']['date'];
            //航班详细信息
            $flightsData = $listAllData['flightItems']['flights'];

            //数据重组
            $flightinfo = array();

            $jjc = 0;
            $swc = 0;
            $tdc = 0;

            if ($listAllData['flightItems']['flights'][0]) {
                foreach ($listAllData['flightItems']['flights'] as $key => $v) {

                    if (isset($v['seatItems'][0])) {
                        $seatItems = $v['seatItems'];
                    } else {
                        $seatItems[0] = $v['seatItems'];
                    }

                    foreach ($seatItems as $ki => $svi) {
                        if ($svi['seatMsg'] == '经济舱' || $svi['seatMsg'] == '高端经济舱' || $svi['seatMsg'] == '超级经济舱' || $svi['seatMsg'] == '特价舱位') {
                            if (($svi['parPrice'] > $jjc) && ($svi['seatMsg'] = '经济舱' || $svi['seatMsg'] == '高端经济舱' || $svi['seatMsg'] == '超级经济舱' || $svi['seatMsg'] == '特价舱位')) {
                                $jjc = $svi['parPrice'];
                            }
                        }

                        if ($svi['seatMsg'] == '商务舱') {
                            if (($svi['parPrice'] > $swc) && ($svi['seatMsg'] = '商务舱')) {
                                $swc = $svi['parPrice'];
                            }
                        }

                        if ($svi['seatMsg'] == '头等舱') {
                            if (($svi['parPrice'] > $tdc) && ($svi['seatMsg'] = '头等舱')) {
                                $tdc = $svi['parPrice'];
                            }
                        }
                    }
                }
            } else {
                $v = $listAllData['flightItems']['flights'];

                if (isset($v['seatItems'][0])) {
                    $seatItems = $v['seatItems'];
                } else {
                    $seatItems[0] = $v['seatItems'];
                }

                foreach ($seatItems as $ki => $svi) {
                    if ($svi['seatMsg'] == '经济舱' || $svi['seatMsg'] == '高端经济舱' || $svi['seatMsg'] == '超级经济舱' || $svi['seatMsg'] == '特价舱位') {
                        if (($svi['parPrice'] > $jjc) && ($svi['seatMsg'] = '经济舱' || $svi['seatMsg'] == '高端经济舱' || $svi['seatMsg'] == '超级经济舱' || $svi['seatMsg'] == '特价舱位')) {
                            $jjc = $svi['parPrice'];
                        }
                    }

                    if ($svi['seatMsg'] == '商务舱') {
                        if (($svi['parPrice'] > $swc) && ($svi['seatMsg'] = '商务舱')) {
                            $swc = $svi['parPrice'];
                        }
                    }

                    if ($svi['seatMsg'] == '头等舱') {
                        if (($svi['parPrice'] > $tdc) && ($svi['seatMsg'] = '头等舱')) {
                            $tdc = $svi['parPrice'];
                        }
                    }
                }
            }

            if ($listAllData['flightItems']['flights'][0]) {
                foreach ($listAllData['flightItems']['flights'] as $key => $v) {
                    //航班信息重组
                    $deptime = substr($v['depTime'], 0, 2) . ':' . substr($v['depTime'], 2, 2);
                    $arrtime = substr($v['arriTime'], 0, 2) . ':' . substr($v['arriTime'], 2, 2);
                    $flightinfo[$key]['orgCity'] = $v['orgCity'];
                    $flightinfo[$key]['depname'] = $this->nameToAirport($v['orgCity']);
                    $flightinfo[$key]['depTime'] = $deptime;
                    $flightinfo[$key]['dstCity'] = $v['dstCity'];
                    $flightinfo[$key]['arrname'] = $this->nameToAirport($v['dstCity']);
                    $flightinfo[$key]['arriTime'] = $arrtime;
                    //$flightinfo[$key]['flightNo'] = substr($v['flightNo'], 0, 2);
                    $flightinfo[$key]['flightNo'] = $v['flightNo'];
                    $flightinfo[$key]['flightNoLetter'] = substr($v['flightNo'], 0, 2);
                    $flightinfo[$key]['planeType'] = $v['planeType'];
                    $flightinfo[$key]['dstJetquay'] = (string) $v['dstJetquay'];
                    $flightinfo[$key]['orgJetquay'] = (string) $v['orgJetquay'];
                    $flightinfo[$key]['fuelTax'] = $listAllData['flightItems']['audletFuelTax'];
                    $flightinfo[$key]['airportTax'] = $listAllData['flightItems']['audletAirportTax'];
                    $flightinfo[$key]['share'] = $v['codeShare'];
                    $flightinfo[$key]['stop'] = $v['stopnum'];
                    $flightinfo[$key]['day'] = $v['param1'];
                    $days = $v['param1'] . " " . $deptime;
                    $flightinfo[$key]['days'] = date("YmdHis", strtotime($days));

                    if (isset($v['seatItems'][0])) {
                        $seatItems = $v['seatItems'];
                    } else {
                        $seatItems[0] = $v['seatItems'];
                    }

                    //仓位重组
                    foreach ($seatItems as $k => $sv) {
                        $seatcode = strval($sv['seatCode']);
                        $flightinfo[$key]['price'][$k]['id'] = $k;
                        $flightinfo[$key]['price'][$k]['seatMsg'] = $sv['seatMsg'];
                        $flightinfo[$key]['price'][$k]['ticketnum'] = $sv['seatStatus'];
                        $flightinfo[$key]['price'][$k]['agio'] = $sv['discount'];
                        $flightinfo[$key]['price'][$k]['seatCode'] = $sv['seatCode'];
                        $flightinfo[$key]['price'][$k]['policyId'] = $sv['policyData']['policyId'];
                        //价格重组
                        $flightinfo[$key]['price'][$k]['parPrice'] = $sv['parPrice'];
                        $flightinfo[$key]['price'][$k]['settlePrice'] = $sv['settlePrice'];
                        $flightinfo[$key]['price'][$k]['earnPrice'] = $sv['parPrice'] - $sv['settlePrice'];

                        if ($sv['seatCode'] == 'J') {
                            $flightinfo[$key]['price'][$k - 1]['specialParPrice'] = $sv['parPrice'];
                        }


                        if ($sv['seatMsg'] == '经济舱' || $sv['seatMsg'] == '高端经济舱' || $sv['seatMsg'] == '超级经济舱' || $sv['seatMsg'] == '特价舱位') {
                            $flightinfo[$key]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $jjc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $jjc, 0, 4), 3, 1);
                        } else if ($sv['seatMsg'] == '商务舱') {
                            $flightinfo[$key]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $swc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $swc, 0, 4), 3, 1);
                        } else if ($sv['seatMsg'] == '头等舱') {
                            $flightinfo[$key]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $tdc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $tdc, 0, 4), 3, 1);
                        }
                    }
                }
            } else {
                $v = $listAllData['flightItems']['flights'];
                //航班信息重组
                $deptime = substr($v['depTime'], 0, 2) . ':' . substr($v['depTime'], 2, 2);
                $arrtime = substr($v['arriTime'], 0, 2) . ':' . substr($v['arriTime'], 2, 2);
                $flightinfo[0]['orgCity'] = $v['orgCity'];
                $flightinfo[0]['depname'] = $this->nameToAirport($v['orgCity']);
                $flightinfo[0]['depTime'] = $deptime;
                $flightinfo[0]['dstCity'] = $v['dstCity'];
                $flightinfo[0]['arrname'] = $this->nameToAirport($v['dstCity']);
                $flightinfo[0]['arriTime'] = $arrtime;
                $flightinfo[0]['flightNo'] = $v['flightNo'];
                $flightinfo[0]['flightNoLetter'] = substr($v['flightNo'], 0, 2);
                $flightinfo[0]['planeType'] = $v['planeType'];
                $flightinfo[0]['dstJetquay'] = (string) $v['dstJetquay'];
                $flightinfo[0]['orgJetquay'] = (string) $v['orgJetquay'];
                $flightinfo[0]['fuelTax'] = $listAllData['flightItems']['audletFuelTax'];
                $flightinfo[0]['airportTax'] = $listAllData['flightItems']['audletAirportTax'];
                $flightinfo[0]['share'] = $v['codeShare'];
                $flightinfo[0]['stop'] = $v['stopnum'];
                $flightinfo[0]['day'] = $v['param1'];
                $days = $v['param1'] . " " . $deptime;
                $flightinfo[0]['days'] = date("YmdHis", strtotime($days));

                if (isset($v['seatItems'][0])) {
                    $seatItems = $v['seatItems'];
                } else {
                    $seatItems[0] = $v['seatItems'];
                }

                //仓位重组
                foreach ($seatItems as $k => $sv) {
                    $seatcode = strval($sv['seatCode']);
                    $flightinfo[0]['price'][$k]['id'] = $k;
                    $flightinfo[0]['price'][$k]['seatMsg'] = $sv['seatMsg'];
                    $flightinfo[0]['price'][$k]['ticketnum'] = $sv['seatStatus'];
                    $flightinfo[0]['price'][$k]['agio'] = $sv['discount'];
                    $flightinfo[0]['price'][$k]['seatCode'] = $sv['seatCode'];
                    $flightinfo[0]['price'][$k]['policyId'] = $sv['policyData']['policyId'];
                    //价格重组
                    $flightinfo[0]['price'][$k]['parPrice'] = $sv['parPrice'];
                    $flightinfo[0]['price'][$k]['settlePrice'] = $sv['settlePrice'];
                    $flightinfo[0]['price'][$k]['earnPrice'] = $sv['parPrice'] - $sv['settlePrice'];

                    if ($sv['seatCode'] == 'J') {
                        $flightinfo[0]['price'][$k - 1]['specialParPrice'] = $sv['parPrice'];
                    }

                    if ($sv['seatMsg'] == '经济舱' || $sv['seatMsg'] == '高端经济舱' || $sv['seatMsg'] == '超级经济舱' || $sv['seatMsg'] == '特价舱位') {
                        $flightinfo[0]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $jjc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $jjc, 0, 4), 3, 1);
                    } else if ($sv['seatMsg'] == '商务舱') {
                        $flightinfo[0]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $swc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $swc, 0, 4), 3, 1);
                    } else if ($sv['seatMsg'] == '头等舱') {
                        $flightinfo[0]['price'][$k]['discount'] = substr_replace(substr(substr($sv['settlePrice'] / $tdc, 0, 4), 2, 2), '.', 1) . substr(substr($sv['settlePrice'] / $tdc, 0, 4), 3, 1);
                    }
                }
            }

            $nowDay = date("Ymd", time());
            $nowDate = date('Ymd', strtotime("$date"));

            if ($nowDate < $nowDay) {
                $departure = $this->nameToAirport(I('departure'));
                $destination = $this->nameToAirport(I('destination'));
                $msg = '很抱歉，暂未查询到符合您要求的航班。您可以调整出行时间或目的地重新查询。';
                $this->assign('msg', $msg);
                $this->assign('departure', $departure);
                $this->assign('destination', $destination);
                $this->display("WxJsAPI/flightQueryError");
                exit();
            }


            $domain = $_SERVER['SERVER_NAME'];
            $domain = "http://" . $domain;
            $this->assign('domain', $domain);

            $agencyInfo = $this->userInfo;
            $mobile = $agencyInfo['mobile'];

            $this->assign('mobile', $mobile);
            $now = date("YmdHis", strtotime('+2 hour'));
            $this->assign('now', $now);
            $this->assign('nowDay', $nowDay);
            $this->assign('nowDate', $nowDate);
            $this->assign('date', $date);
            $this->assign('flightinfo', $flightinfo);
            $this->display();
        }
    }

    /**
     * 创建订单页
     */
    public function createOrder() {
        if (IS_GET) {
            //使用jsapi接口
            $jsApi = new \JsApi_pub();
            $openid = session('openid');
            $accessToken = $jsApi->getAccessToken();
            $visitorWxInfo = $jsApi->getAccessTokenOpenId($accessToken, $openid);

            session('subscribe', $visitorWxInfo['subscribe']);
            session('nickname', $visitorWxInfo['nickname']);
            session('sex', $visitorWxInfo['sex']);
            session('language', $visitorWxInfo['language']);
            session('city', $visitorWxInfo['city']);
            session('province', $visitorWxInfo['province']);
            session('country', $visitorWxInfo['country']);
            session('headimgurl', $visitorWxInfo['headimgurl']);
            session('subscribe_time', $visitorWxInfo['subscribe_time']);
            session('remark', $visitorWxInfo['remark']);
            session('groupid', $visitorWxInfo['groupid']);

            //航班日期
            $date = I('date');
            //航班号
            $flightNo = I('flightNo');
            //飞机型号
            $planeModel = I('planeType');
            //仓码
            $seatCode = I('seatCode');

            //出发时间
            $depTime = I('depTime');
            //抵达时间
            $arriTime = I('arriTime');
            //出发城市
            $orgCity = I('orgCity');
            //抵达城市
            $dstCity = I('dstCity');
            //机票价
            $settlePrice = I('settlePrice');
            $settlePrice = Utils::getFen($settlePrice);
            //政策ID
            $policyId = I('policyId');
            //票面价
            $parPrice = I('parPrice');

            //看是否是C舱
            $flightNoLetter = substr($flightNo, 0, 2);
            if (($flightNoLetter == 'MU' || $flightNoLetter == 'CZ' || $flightNoLetter == 'MF' || $flightNoLetter == 'FM') && $seatCode == 'C') {
                $specialParPrice = I('specialParPrice');
                $childPrice = (float) ($specialParPrice / 2);
            } else {
                $childPrice = (float) ($parPrice / 2);
            }

            //儿童价
            $singleDigit = substr($childPrice, -1);

            if ($singleDigit != '0') {
                $childPrice = (float) ($childPrice + 5);
            }

            $childPrice = Utils::getFen($childPrice);
            //出发航站楼
            $orgJetquay = I('orgJetquay');
            //到达航站楼
            $dstJetquay = I('dstJetquay');
            //燃油税
            $fuelTax = I('fuelTax');
            $fuelTax = Utils::getFen($fuelTax);
            //机建费
            $airportTax = I('airportTax');
            $airportTax = Utils::getFen($airportTax);

            $parPriceFen = Utils::getFen($parPrice);
            $adultTotalPrice = $parPriceFen + $fuelTax + $airportTax;
            $childTotalPrice = $childPrice + $fuelTax;

            $allPrice = [$adultTotalPrice, $childTotalPrice];

            $agencyInfo = $this->userInfo;
            $agencyId = $agencyInfo['id'];
            $_SESSION['flightOrderCreate'] = 400;

            $this->assign('parPriceFen', $parPriceFen);
            $this->assign('specialParPrice', $specialParPrice);
            $this->assign('orgJetquay', $orgJetquay);
            $this->assign('dstJetquay', $dstJetquay);
            $this->assign('allPrice', $allPrice);
            $this->assign('date', $date);
            $this->assign('flightNo', $flightNo);
            $this->assign('planeModel', $planeModel);
            $this->assign('seatCode', $seatCode);
            $this->assign('depTime', $depTime);
            $this->assign('arriTime', $arriTime);
            $this->assign('orgCity', $orgCity);
            $this->assign('dstCity', $dstCity);
            $this->assign('settlePrice', $settlePrice);
            $this->assign('childPrice', $childPrice);
            $this->assign('policyId', $policyId);
            $this->assign('agencyId', $agencyId);
            $this->assign('parPrice', $parPrice);
            $this->assign('fuelTax', $fuelTax);
            $this->assign('airportTax', $airportTax);
            $this->assign('adultTotalPrice', $adultTotalPrice);
            $this->assign('childTotalPrice', $childTotalPrice);
            $this->display("WxJsAPI/createOrder");
        } else if (IS_POST) {
            $agencyInfo = $this->userInfo;
            $dataList = I('post.');

            $count = I('passenger-num');

            if (empty($count)) {
                $count = 1;
            }

            $numSum = 0;
            $names = '';
            for ($i = 1; $i <= $count; $i++) {
                $identityNo = identityNo . $i;
                $where['identity_no'] = $dataList[$identityNo];
                $where['flight_no'] = $dataList['flightNo'];
                $where['dep_date'] = $dataList['depDate'];
                $where['agency_id'] = $agencyInfo['id'];
                $map['state'] = array('in', '14,15,2,3');
                $detailNum = M('visitor_order_flight_detail')->where($where)->where($map)->find();

                if ($detailNum) {
                    $names .= $detailNum['passenger_name'] . ",";
                    $numSum += 1;
                }
            }

            $postCode = I('flightOrderCreate');
            $code = session('flightOrderCreate');

            if ($code == $postCode && $numSum == 0) {
                session('flightOrderCreate', null);
                $parPrice = (float) I('parPrice');
                $fuelTax = (float) Utils::getYuan(I('fuelTax'));
                $airportTax = (float) Utils::getYuan(I('airportTax'));

                $orderParPrice = (float) I('settlePrice');
                $orderFuelTax = (float) I('fuelTax');
                $orderAirportTax = (float) I('airportTax');

                $agencyInfo = $this->userInfo;
                $agencyId = $agencyInfo['id'];
                $outOrderNo = "S" . rand(1000, 9999) . time();

                for ($i = 1; $i <= $count; $i++) {
                    $name = name . $i;
                    $type = type . $i;
                    $identityType = identityType . $i;
                    $identityNo = identityNo . $i;
                    $birthday = birthday . $i;
                    $orderFlightData['visitor_openid'] = session('openid');
                    $orderFlightData['subscribe'] = session('subscribe');
                    $orderFlightData['nickname'] = preg_replace("/[^\x{4e00}-\x{9fa5}]/iu", '', session('nickname'));
                    $orderFlightData['nickname_base64'] = base64_encode(session('nickname'));
                    $orderFlightData['sex'] = session('sex');
                    $orderFlightData['language'] = session('language');
                    $orderFlightData['city'] = session('city');
                    $orderFlightData['province'] = session('province');
                    $orderFlightData['country'] = session('country');
                    $orderFlightData['headimgurl'] = session('headimgurl');
                    $orderFlightData['subscribe_time'] = date("Y-m-d H:i:s", session('subscribe_time'));
                    $orderFlightData['remark'] = session('remark');
                    $orderFlightData['groupid'] = session('groupid');
                    $orderFlightData['passenger_name'] = Utils::trimall($dataList[$name]);
                    $orderFlightData['passenger_type'] = $dataList[$type];
                    $orderFlightData['identity_type'] = $dataList[$identityType];
                    $orderFlightData['identity_no'] = $dataList[$identityNo];
                    $orderFlightData['birthday'] = $dataList[$birthday];
                    $orderFlightData['agency_id'] = $agencyId;
                    $orderFlightData['flight_no'] = $dataList['flightNo'];
                    $orderFlightData['dep_code'] = $dataList['depCode'];
                    $orderFlightData['arr_code'] = $dataList['arrCode'];
                    $orderFlightData['seat_class'] = $dataList['seatCode'];
                    $orderFlightData['dep_date'] = $dataList['depDate'];
                    $orderFlightData['dep_time'] = str_replace(':', '', $dataList['depTime']);
                    $orderFlightData['arr_time'] = str_replace(':', '', $dataList['arrTime']);
                    $orderFlightData['plane_model'] = $dataList['planeModel'];
                    $orderFlightData['settle_price'] = $orderParPrice;
                    $orderFlightData['par_price'] = Utils::getFen($parPrice);
                    $orderFlightData['fuel_tax'] = $orderFuelTax;
                    $orderFlightData['airport_tax'] = $orderAirportTax;
                    $orderFlightData['policy_id'] = $dataList['policyId'];
                    $orderFlightData['link_man'] = $dataList['linkMan'];
                    $orderFlightData['link_phone'] = $dataList['linkPhone'];
                    $orderFlightData['out_order_no'] = $outOrderNo;
                    $orderFlightData['state'] = 1;
                    $orderFlightData['create_time'] = date("Y-m-d H:i:s", time());
                    $result = M('visitor_order_flight_detail')->add($orderFlightData);
                }

                //看是否是C舱
                $seatCode = $dataList['seatCode'];
                $flightNo = $dataList['flightNo'];
                $flightNoLetter = substr($flightNo, 0, 2);

                if (($flightNoLetter == 'MU' || $flightNoLetter == 'CZ' || $flightNoLetter == 'MF' || $flightNoLetter == 'FM') && $seatCode == 'C') {
                    $specialParPrice = I('specialParPrice');
                    $childPrice = (float) ($specialParPrice / 2);
                } else {
                    $childPrice = (float) ($parPrice / 2);
                }

                $singleDigit = substr($childPrice, -1);

                if ($singleDigit != '0') {
                    $childPrice = (float) ($childPrice + 5);
                }

                $childPrice = Utils::getFen($childPrice);

                $childFlightData['settle_price'] = (float) ($childPrice);

                $childFlightData['par_price'] = (float) ($childPrice);
                $childFlightData['airport_tax'] = 0;
                //更新儿童价
                $childInfo = M('visitor_order_flight_detail')->where("out_order_no = '{$outOrderNo}' && passenger_type = 1")->find();
                if ($childInfo) {
                    $childResult = M('visitor_order_flight_detail')->where("out_order_no = '{$outOrderNo}' && passenger_type = 1")->save($childFlightData);
                }

                $passengerNames = array();
                for ($i = 1; $i <= $count; $i++) {
                    $name = name . $i;
                    $passengerNames[$i]['passenger_name'] = $dataList[$name];
                }

                $passengerName = array_column($passengerNames, 'passenger_name');
                $passengerName = implode(",", $passengerName);

                $orderData['agency_name'] = $agencyInfo['name'];
                $orderData['passenger_names'] = $passengerName;
                $orderData['passenger_total'] = $count;
                $orderData['passenger_adult'] = count(M('visitor_order_flight_detail')->where("out_order_no = '{$outOrderNo}' && passenger_type = 0")->select());
                $orderData['passenger_child'] = count(M('visitor_order_flight_detail')->where("out_order_no = '{$outOrderNo}' && passenger_type = 1")->select());

                if ($orderData['passenger_child'] == 0) {
                    $orderData['price_total'] = $orderData['passenger_adult'] * Utils::getFen($parPrice) + $orderData['passenger_adult'] * $orderFuelTax + $orderData['passenger_adult'] * $orderAirportTax;
                } else {
                    $orderData['price_total'] = $orderData['passenger_adult'] * Utils::getFen($parPrice) + $orderData['passenger_adult'] * $orderFuelTax + $orderData['passenger_adult'] * $orderAirportTax + $orderData['passenger_child'] * $childPrice + $orderData['passenger_child'] * $orderFuelTax + 500;
                }

                $orderData['agency_id'] = I('agencyId');
                $orderData['operator_id'] = $agencyInfo['operator_id'];
                $orderData['org_jetquay'] = I('orgJetquay');
                $orderData['dst_jetquay'] = I('dstJetquay');
                $orderData['state'] = 1;
                $orderData['visitor_openid'] = session('openid');
                $orderData['subscribe'] = session('subscribe');
                $orderData['nickname'] = preg_replace("/[^\x{4e00}-\x{9fa5}]/iu", '', session('nickname'));
                $orderData['nickname_base64'] = base64_encode(session('nickname'));
                $orderData['sex'] = session('sex');
                $orderData['language'] = session('language');
                $orderData['city'] = session('city');
                $orderData['province'] = session('province');
                $orderData['country'] = session('country');
                $orderData['headimgurl'] = session('headimgurl');
                $orderData['subscribe_time'] = date("Y-m-d H:i:s", session('subscribe_time'));
                $orderData['remark'] = session('remark');
                $orderData['groupid'] = session('groupid');
                $orderData['create_time'] = date("Y-m-d H:i:s", time());

                $orderFlightResult = M('visitor_order_flight')->add($orderData);

                $orderFlightDetailData['order_flight_id'] = $orderFlightResult;
                $orderFlightDataResult = M('visitor_order_flight_detail')->where("out_order_no = '{$outOrderNo}'")->save($orderFlightDetailData);

                //向平台提交订单
                $orderFlightAdultList = M('visitor_order_flight_detail')->where("agency_id = '{$agencyId}' && order_flight_id = '{$orderFlightResult}' && passenger_type = 0")->select();
                $orderFlightChildList = M('visitor_order_flight_detail')->where("agency_id = '{$agencyId}' && order_flight_id = '{$orderFlightResult}' && passenger_type = 1")->select();

                foreach ($orderFlightAdultList as $val) {
                    $adultPassengers[] = array(
                        'name' => str_replace(' ', '/', $val['passenger_name']),
                        'type' => (int) $val['passenger_type'],
                        'identityType' => $val['identity_type'],
                        'identityNo' => $val['identity_no'],
                        'birthday' => $val['birthday'],
                    );
                }

                foreach ($orderFlightChildList as $val) {
                    $childPassengers[] = array(
                        'name' => str_replace(' ', '/', $val['passenger_name']),
                        'type' => (int) $val['passenger_type'],
                        'identityType' => $val['identity_type'],
                        'identityNo' => $val['identity_no'],
                        'birthday' => $val['birthday'],
                    );
                }

                foreach ($orderFlightAdultList as $val) {
                    //航段信息
                    $segments = array(
                        'flightNo' => $val['flight_no'],
                        'depCode' => $val['dep_code'],
                        'arrCode' => $val['arr_code'],
                        'seatClass' => $val['seat_class'],
                        'depDate' => $val['dep_date'],
                        'depTime' => $val['dep_time'],
                        'arrTime' => $val['arr_time'],
                        'planeModel' => $val['plane_model'],
                    );
                }

                $parPrice = (float) Utils::getYuan($orderFlightAdultList[0]['par_price']);
                $fuelTax = (float) Utils::getYuan($orderFlightAdultList[0]['fuel_tax']);
                $airportTax = (float) Utils::getYuan($orderFlightAdultList[0]['airport_tax']);

                //成人 提交
                $adultPnrInfo = array(
                    'segments' => $segments,
                    'passengers' => $adultPassengers,
                    'parPrice' => $parPrice,
                    'fuelTax' => $fuelTax,
                    'airportTax' => $airportTax,
                );

                $outOrderNo = "S" . rand(1000, 9999) . time();
                $policyId = $orderFlightAdultList[0]['policy_id'];
                $adultOrderData = array(
                    'agencyCode' => $this->agencyCode(),
                    'policyId' => $policyId,
                    'sign' => md5($this->agencyCode() . $policyId . $this->sign()),
                    'linkMan' => $orderFlightAdultList[0]['link_man'],
                    'linkPhone' => $orderFlightAdultList[0]['link_phone'],
                    'notifiedUrl' => 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/orderSuccessNotify',
                    'paymentReturnUrl' => 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/paymentReturn',
                    'outOrderNo' => $outOrderNo,
                    'pnrInfo' => $adultPnrInfo,
                    'allowSwitchPolicy' => 0,
                    'needSpeRulePolicy' => 0,
                );

                //十位取整
                //看是否是C舱
                $seatCode = I('seatCode');
                $flightNo = I('flightNo');
                $flightNoLetter = substr($flightNo, 0, 2);

                if (($flightNoLetter == 'MU' || $flightNoLetter == 'CZ' || $flightNoLetter == 'MF' || $flightNoLetter == 'FM') && $seatCode == 'C') {
                    $specialParPrice = I('specialParPrice');
                    $childPrice = (float) ($specialParPrice / 2);
                } else {
                    $childPrice = (float) ($parPrice / 2);
                }

                $singleDigit = substr($childPrice, -1);

                if ($singleDigit != '0') {
                    $childPrice = (float) ($childPrice + 5);
                }

                //儿童 提交
                $childPnrInfo = array(
                    'segments' => $segments,
                    'passengers' => $childPassengers,
                    'parPrice' => $childPrice,
                    'fuelTax' => $fuelTax,
                    'airportTax' => 0.0,
                );

                $childOrderData = array(
                    'agencyCode' => $this->agencyCode(),
                    'policyId' => '0',
                    'sign' => md5($this->agencyCode() . 0 . $this->sign()),
                    'linkMan' => $orderFlightAdultList[0]['link_man'],
                    'linkPhone' => $orderFlightAdultList[0]['link_phone'],
                    'notifiedUrl' => 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/orderSuccessNotify',
                    'paymentReturnUrl' => 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/paymentReturn',
                    'outOrderNo' => $outOrderNo,
                    'pnrInfo' => $childPnrInfo,
                    'allowSwitchPolicy' => 0,
                    'needSpeRulePolicy' => 0,
                );

                //返回 数组 格式

                $adultOrderResult = Api_51::orderCreate($adultOrderData);
                $adultOrderArr = $this->object_to_array($adultOrderResult);

                if ($orderFlightChildList) {
                    $childOrderResult = Api_51::orderCreate($childOrderData);
                    $childOrderArr = $this->object_to_array($childOrderResult);
                }

                //返回值
                $returnCode = $adultOrderArr['return']['returnCode'];
                $childReturnCode = $childOrderArr['return']['returnCode'];

                if ($returnCode !== 'S' || (isset($childOrderArr) && $childReturnCode !== 'S')) {
                    $msg = $adultOrderArr['return']['returnMessage'] . $childOrderArr['return']['returnMessage'];
                    $this->assign('msg', $msg);
                    $this->display("WxJsAPI/flightQueryError");
                    exit();
                }

                $orderData['state'] = Top::FlightOrderStateWaitingForPayment;
                //有儿童时,两个不同的交易号
                if ($orderFlightChildList) {
                    $adultOrderNo['state'] = Top::FlightOrderStateWaitingForPayment;
                    $adultOrderNo['sequence_no'] = $adultOrderArr['return']['order']['liantuoOrderNo'];

                    $childOrderNo['state'] = Top::FlightOrderStateWaitingForPayment;
                    $childOrderNo['sequence_no'] = $childOrderArr['return']['order']['liantuoOrderNo'];
                    $liantuoOrderNo = $adultOrderNo['sequence_no'] . ";" . $childOrderNo['sequence_no'];
                    $orderData['sequence_no'] = (string) $liantuoOrderNo;

                    $adultFlightDetailSequenceNo = M('visitor_order_flight_detail')->where("order_flight_id = '{$orderFlightResult}' && agency_id = '{$agencyId}' && passenger_type = 0")->save($adultOrderNo);
                    $childFlightDetailSequenceNo = M('visitor_order_flight_detail')->where("order_flight_id = '{$orderFlightResult}' && agency_id = '{$agencyId}' && passenger_type = 1")->save($childOrderNo);
                } else {
                    $adultLiantuoOrderNo = $adultOrderArr['return']['order']['liantuoOrderNo'];
                    $orderData['sequence_no'] = (string) $adultLiantuoOrderNo;
                    $adultOrderData['sequence_no'] = (string) $adultLiantuoOrderNo;
                    $adultOrderData['state'] = Top::FlightOrderStateWaitingForPayment;
                    $flightDetailSequenceNo = M('visitor_order_flight_detail')->where("order_flight_id = '{$orderFlightResult}' && agency_id = '{$agencyId}'")->save($adultOrderData);
                }
                $orderFlightUpdateResult = M('visitor_order_flight')->where("id = '{$orderFlightResult}'")->save($orderData);
                //提交结束

                $domain = $_SERVER['SERVER_NAME'];
                $redirectUrl = 'http://' . $domain;
                $url = 'http://wxpay.m.lydlr.com/index.php/Home/WxJsAPI/jsApiCall/fid/' . $orderFlightResult . ".html?openid=" . session('openid') . "&redirectUrl=" . $redirectUrl;
                Header("Location: $url");
                exit();
            } else {
                $msg = "您有未完成的订单,乘客 " . $names . " 重复下单";
                $this->assign('msg', $msg);
                $this->display("Flight/flightQueryError");
                exit();
            }
        }
    }

    /**
     * 订票 URL 通知
     */
    public function orderSuccessNotify() {
        $data['type'] = I('get.type');
        $data['sequence_no'] = I('get.sequenceNo');
        $data['passenger_names'] = I('get.passengerNames');
        $data['ticket_nos'] = I('get.ticketNos');
        $data['ticket_price'] = I('get.ticketPrice');
        $data['fuel_tax'] = I('get.fuelTax');
        $data['airport_tax'] = I('get.airportTax');
        $data['settle_price'] = I('get.settlePrice');
        $data['pnr_no'] = I('get.pnrNo');
        $data['old_pnr_no'] = I('get.oldPnrNo');
        $data['reason'] = I('get.reason');
        $data['refund_no'] = I('get.refundNo');
        $data['order_no'] = I('get.orderNo');
        $data['refund_time'] = I('get.refundTime');
        $data['refund_price'] = I('get.refundPrice');
        $data['flight_no'] = I('flightNo');
        $data['content'] = I('get.content');
        $data['create_time'] = date("Y-m-d H:i:s", time());

        $sequenceNo = $data['sequence_no'];
        $orderFlightDetails = M('visitor_order_flight_detail')->where("sequence_no = '{$sequenceNo}'")->limit(1)->find();
        $orderFlightInfo = M('visitor_order_flight')->where("sequence_no = '{$sequenceNo}'")->limit(1)->find();
        $orgJetquay = $orderFlightInfo['org_jetquay'];

        if ($orgJetquay) {
            $orgJetquay = $orgJetquay . "出发";
        } else {
            $orgJetquay = '';
        }

        $mobile = $orderFlightDetails['link_phone'];
        $flightNo = $this->nameToAirLine(substr($orderFlightDetails['flight_no'], 0, 2)) . substr($orderFlightDetails['flight_no'], 2);
        $depDate = $orderFlightDetails['dep_date'];
        $depTime1 = $orderFlightDetails['dep_time'];
        $depTime = substr($depTime1, 0, 2) . ':' . substr($depTime1, 2, 2);
        $depCode = $this->nameToFullAirport($orderFlightDetails['dep_code']);

        $nowTime = Utils::getBatch();

        if ($data['type'] == '1') {
            $message = "您预定的 " . $flightNo . " 航班已成功出票, 于" . $depDate . " " . $depTime . "从 " . $depCode . " " . $orgJetquay . " 起飞,客服电话 0551-65238888";

            $where['sequence_no'] = $data['sequence_no'];
            //$where['agency_id'] = $agencyInfo['id'];
            $orderFlightData['state'] = Top::FlightOrderStateTicked;
            $orderFlightData['ticket_no'] = $data['ticket_nos'];
            $orderFlightResult = M('visitor_order_flight')->where($where)->save($orderFlightData);

            $orderFlightDetailList = M('visitor_order_flight_detail')->where($where)->field('id')->select();

            $ticketNos = explode(",", $data['ticket_nos']);
            array_pop($ticketNos);
            $passengerNums = count($ticketNos);

            //判断多人订购还是单人
            if ($passengerNums == 1) {
                $where['id'] = $orderFlightDetailList[0]['id'];
                $orderFlightData['pay_time'] = date('Y-m-d H:i:s', time());
                $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->save($orderFlightData);
            } else {
                for ($i = 0; $i < $passengerNums; $i++) {
                    //$where['ticket_no'] = '';
                    $where['id'] = $orderFlightDetailList[$i]['id'];
                    $orderFlightDetailData['pay_time'] = date('Y-m-d H:i:s', time());
                    $orderFlightDetailData['state'] = Top::FlightOrderStateTicked;
                    $orderFlightDetailData['ticket_no'] = $ticketNos[$i];
                    $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->limit(1)->save($orderFlightDetailData);
                }
            }

            Sms::Send($mobile, $message, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
        } else if ($data['type'] == '2') {
            $sequenceNo = $data['order_no'];
            $flightOrderInfo = M('visitor_order_flight')->where("sequence_no = '{$sequenceNo}'")->find();
            $priceTotal = $flightOrderInfo['price_total'];
            $flightId = $flightOrderInfo['id'];

            //$operatorId = $flightOrderInfo['operator_id'];
            $operatorResult = M('sys')->where("id = 1")->setInc('account_credit_balance', $priceTotal);

            $operatorList = M('sys')->where("id = 1")->find();
            $agencyData['operator_id'] = 1;
            $agencyData['action'] = '冲正:机票订单款';
            $agencyData['entity_type'] = Top::EntityTypeSystem;
            $agencyData['entity_id'] = 1;
            $agencyData['account'] = $operatorList['account'];
            $agencyData['sn'] = Utils::getSn();
            $agencyData['batch'] = $nowTime;
            $agencyData['amount'] = $priceTotal;
            $agencyData['balance'] = $operatorList['account_credit_balance'];
            $agencyData['create_time'] = date('Y-m-d H:i:s', time());
            $agencyData['remark'] = 'top_visitor_order_flight.id:' . $flightId;
            $agencyData['object_id'] = $flightId;
            $agencyData['object_type'] = Top::ObjectTypeFlight;
            $agencyData['object_name'] = '机票';
            $agencyDelmoney = M('operator_credit_transaction')->add($agencyData);

            $message = "您预定的 " . $flightNo . " 航班出票失败, 请联系相关工作人员,客服电话 0551-65238888";

            $where['sequence_no'] = $data['sequence_no'];
            $orderFlightData['state'] = Top::FlightOrderStateTicketFailed;
            $orderFlightData['ticket_no'] = $data['ticket_nos'];
            $orderFlightResult = M('visitor_order_flight')->where($where)->save($orderFlightData);

            $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->save($orderFlightData);

            Sms::Send($mobile, $message, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
        } else if ($data['type'] == '3') {

            $flightOrderInfo = M('visitor_order_flight')->where("sequence_no = '{$sequenceNo}'")->find();
            $priceTotal = $flightOrderInfo['price_total'];
            $flightId = $flightOrderInfo['id'];

            //$operatorId = $flightOrderInfo['operator_id'];
            $operatorResult = M('sys')->where("id = 1")->setInc('account_credit_balance', $priceTotal);

            $operatorList = M('sys')->where("id = 1")->find();
            $agencyData['operator_id'] = 1;
            $agencyData['action'] = '冲正:机票订单款';
            $agencyData['entity_type'] = Top::EntityTypeSystem;
            $agencyData['entity_id'] = 1;
            $agencyData['account'] = $operatorList['account'];
            $agencyData['sn'] = Utils::getSn();
            $agencyData['batch'] = $nowTime;
            $agencyData['amount'] = $priceTotal;
            $agencyData['balance'] = $operatorList['account_credit_balance'];
            $agencyData['create_time'] = date('Y-m-d H:i:s', time());
            $agencyData['remark'] = 'top_visitor_order_flight.id:' . $flightId;
            $agencyData['object_id'] = $flightId;
            $agencyData['object_type'] = Top::ObjectTypeFlight;
            $agencyData['object_name'] = '机票';
            $agencyDelmoney = M('operator_credit_transaction')->add($agencyData);

            $message = "您预定的 " . $flightNo . " 航班预定失败, 请联系相关工作人员,客服电话 0551-65238888";

            $where['sequence_no'] = $data['sequence_no'];
            $orderFlightData['state'] = Top::FlightOrderStateScheduledFailed;
            $orderFlightData['ticket_no'] = $data['ticket_nos'];
            $orderFlightResult = M('visitor_order_flight')->where($where)->save($orderFlightData);

            $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->save($orderFlightData);

            Sms::Send($mobile, $message, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
        }

        $state = I('get.type');
        if ($state == '1' || $state == '2' || $state == '3' || $state == '0') {
            $result = M('log_order_flight')->add($data);
            echo 'S';
        }
    }

    /**
     * 支付 URL 通知
     */
    public function paymentReturn() {
        $data['sequence_no'] = I('sequenceNo');
        $data['buyer_payment_account'] = I('get.buyerPaymentAccount');
        $data['pre_charge'] = I('get.preCharge');
        $data['order_status'] = I('get.orderStatus');
        $data['create_time'] = date("Y-m-d H:i:s", time());
        $result = M('log_order_payment')->add($data);
    }

    /**
     * 退票 URL 通知
     */
    public function refundNotify() {
        $data['sequence_no'] = I('get.sequenceNo');
        $data['order_no'] = I('get.orderNo');
        $data['vender_refund_time'] = I('get.venderRefundTime');
        $data['vender_pay_price'] = I('get.venderPayPrice');
        $data['refund_fee'] = I('get.refundFee');
        $data['out_refund_no'] = I('get.outRefundNo');
        $data['vender_remark'] = I('get.venderRemark');
        $data['type'] = I('get.type');
        $data['create_time'] = date("Y-m-d H:i:s", time());

        $agencyInfo = $this->userInfo;
        if ($data['type'] == '1') {
            $where['sequence_no'] = $data['sequence_no'];
            $where['agency_id'] = $agencyInfo['id'];
            $orderFlightData['state'] = Top::FlightOrderStateRefunded;
            $orderFlightResult = M('visitor_order_flight')->where($where)->save($orderFlightData);

            $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->save($orderFlightData);
        } else if ($data['type'] == '0') {
            $where['sequence_no'] = $data['sequence_no'];
            $where['agency_id'] = $agencyInfo['id'];
            $orderFlightData['state'] = Top::FlightOrderStateRefundFailed;
            $orderFlightResult = M('visitor_order_flight')->where($where)->save($orderFlightData);

            $orderFlightDetailResult = M('visitor_order_flight_detail')->where($where)->save($orderFlightData);
        }

        $state = I('get.type');
        if ($state == '1' || $state == '2' || $state == '3' || $state == '0') {
            $result = M('log_refund_ticket_flight')->add($data);
            echo 'S';
        }
    }

    /**
     * 我的机票
     */
    public function myPlaneTicket() {
        $page = I('page');

        if ($page == '') {
            $page = 1;
        }

        $html = $this->planeTicketListGetPageHtml($page);

        if (IS_POST && IS_AJAX) {
            $this->ajaxReturn($html);
        } else {
            $this->assign('html', $html);
        }

        $this->display();
    }

    /**
     * 订单退废票
     */
    public function orderRefund() {
        $url = $this->orderRefundUrl();
        $data['agencyCode'] = $this->agencyCode();
        $data['liantuoOrderNo'] = '112015112568579717';         //单号
        $data['actionType'] = '3';
        $data['refundType'] = 'APPLY_FOR_REFUND_FREEWILL';
        $data['refundTicketList.passengerName'] = '王珏';       //退票时,输入乘客的姓名
        $data['refundTicketList.ticketNo'] = '999-9743523403';  //必须13位,支付成功后,通知上附带票号信息
        $data['refundTicketList.segment'] = 'PEK-CIF';          //出发 - 到达目的地
        $data['cancelPnrStatus'] = '1';
        $data['refundNotifiedUrl'] = 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/refundNotify';
        $sign = $data['actionType'] . $this->agencyCode() . $this->sign();
        $data['sign'] = strtolower(md5($sign));
        //返回 xml 格式
        $result = Utils::vpost($url, $data);
        //转换成数组
        $listAllData = $this->xml_to_array($result);
    }

    /**
     * 退票
     */
    public function refundApplication() {
        if (IS_POT && IS_AJAX) {
            $url = $this->orderRefundUrl();
            $data['agencyCode'] = $this->agencyCode();
            $data['liantuoOrderNo'] = I('orderNo');         //单号
            $data['actionType'] = '3';
            $data['refundType'] = 'APPLY_FOR_REFUND_FREEWILL';
            $data['refundTicketList.passengerName'] = I('passengerName');       //退票时,输入乘客的姓名
            $data['refundTicketList.ticketNo'] = I('ticketNo');  //必须13位,支付成功后,通知上附带票号信息
            //$depCode =
            $data['refundTicketList.segment'] = I('segment');          //出发 - 到达目的地
            $data['cancelPnrStatus'] = '1';
            $data['refundNotifiedUrl'] = 'http://zhangda.m.lydlr.com/index.php/Home/WxJsAPI/refundNotify';
            $sign = $data['actionType'] . $this->agencyCode() . $this->sign();
            $data['sign'] = strtolower(md5($sign));

            $ticketNo = explode(",", I('ticketNo'));
            $ticketNo = $ticketNo[0];
            //返回 xml 格式
            $result = Utils::vpost($url, $data);
            //转换成数组
            $listAllData = $this->xml_to_array($result);
            $returnCode = $listAllData['returnCode'][0];
            //dump($listAllData);
            if ($returnCode == 'S') {
                $state = Top::FlightOrderStateRefundWaited;
                $sequence_no = I('orderNo');
                $result = M('visitor_order_flight')->execute("update top_visitor_order_flight set state = '{$state}' where sequence_no = '{$sequence_no}'");

                $orderFlightDetailResult = M('visitor_order_flight_detail')->execute("update top_visitor_order_flight_detail set state = '{$state}' where sequence_no = '{$sequence_no}' && ticket_no = '{$ticketNo}'");

                $data['status'] = 1;
                $data['msg'] = '退票中,待退款';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 2;
                $data['msg'] = $listAllData['returnMessage'][0];
                $this->ajaxReturn($data);
            }
        } else {
            $ticket_no = I('get.ticket_no');
            $sequence_no = I('get.sequence_no');
            $flightInfo = M('visitor_order_flight_detail')->where("ticket_no = '{$ticket_no}' && sequence_no = '{$sequence_no}'")->find();
            $this->assign('flightInfo', $flightInfo);
            $this->display();
        }
    }

    /**
     * [planeTicketListGetPageHtml 我的机票 加载更多]
     */
    protected function planeTicketListGetPageHtml($page) {
        $M = M();
        $openId = session('openid');
        $state = Top::FlightOrderStateDeleted;

        //每页显示数量
        $pageSize = C('PRODUCT_PAGE_SET');
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_visitor_order_flight_detail as d,top_visitor_order_flight as f')
                //->where("f.sequence_no = d.sequence_no && f.id = d.order_flight_id && d.visitor_openid = '{$openId}' && d.state != '{$state}' && f.state != '{$state}'")
                ->where("f.id = d.order_flight_id && d.visitor_openid = '{$openId}' && d.state != '{$state}' && f.state != '{$state}'")
                ->field(array(
                    'f.id' => 'id',
                    'd.flight_no' => 'flight_no',
                    'd.sequence_no' => 'sequence_no',
                    'd.seat_class' => 'seat_class',
                    'd.dep_code' => 'dep_code',
                    'd.arr_code' => 'arr_code',
                    'd.dep_date' => 'dep_date',
                    'd.dep_time' => 'dep_time',
                    'd.arr_time' => 'arr_time',
                    'd.plane_model' => 'plane_model',
                    'f.passenger_names' => 'passenger_name',
                    'f.org_jetquay' => 'org_jetquay',
                    'f.dst_jetquay' => 'dst_jetquay',
                    'f.create_time' => 'create_time',
                    'f.price_total' => 'price_total',
                    'f.state' => 'state',
                ))
                ->order('f.id desc')
                ->group('d.order_flight_id')
                ->limit($index, $pageSize)
                ->select();


        foreach ($list as $key => $vo) {
            $vo['passenger_name'] = str_replace(",", " ", $vo['passenger_name']);

            if ($vo['org_jetquay'] == '--' || $vo['org_jetquay'] == 'Array') {
                $vo['org_jetquay'] = '';
            }

            if ($vo['dst_jetquay'] == '--' || $vo['dst_jetquay'] == 'Array') {
                $vo['dst_jetquay'] = '';
            }

            if ($vo['state'] == 1) {
                $orderState = "未提交";
            } else if ($vo['state'] == 2) {
                $orderState = "已付款,待出票";
            } else if ($vo['state'] == 3) {
                $orderState = "已付款,已出票";
            } else if ($vo['state'] == 4) {
                $orderState = "已取消";
            } else if ($vo['state'] == 5) {
                $orderState = "已退票,退票成功";
            } else if ($vo['state'] == 6) {
                $orderState = "出票失败";
            } else if ($vo['state'] == 7) {
                $orderState = "预定失败";
            } else if ($vo['state'] == 8) {
                $orderState = "退票失败";
            } else if ($vo['state'] == 9) {
                $orderState = "退票中,待退款";
            } else if ($vo['state'] == 10) {
                $orderState = "有取消";
            } else if ($vo['state'] == 11) {
                $orderState = "有退票";
            } else if ($vo['state'] == 12) {
                $orderState = "已删除";
            } else if ($vo['state'] == 14) {
                $orderState = "已预定,待付款";
            } else if ($vo['state'] == 15) {
                $orderState = "已预定,付款中";
            }

            $vo['flight_no'] = $this->nameToAirLine(substr($vo['flight_no'], 0, 2)) . " " . $vo['flight_no'];

            $vo['start_code'] = $this->nameToAirport($vo['dep_code']);
            $vo['end_code'] = $this->nameToAirport($vo['arr_code']);

            $vo['dep_code'] = $this->nameToFullAirport($vo['dep_code']);
            $vo['arr_code'] = $this->nameToFullAirport($vo['arr_code']);

            $vo['price_total'] = Utils::getYuan($vo['price_total']);


            $vo['dep_time'] = substr($vo['dep_time'], 0, 2) . ':' . substr($vo['dep_time'], 2, 2);
            $vo['arr_time'] = substr($vo['arr_time'], 0, 2) . ':' . substr($vo['arr_time'], 2, 2);

            $refund = "<a href=" . U('WxJsAPI/planeTicketDetail', array('id' => $vo['id'])) . ">
                    <input type='button' class='btn btn-warning' style='float:right;margin-top:-6px;' value='查看详情'>
                    </a>";

            $evaldata .= "<ul class='tradeList' style='height:100%'>";
            $evaldata .= "<li>";
            $evaldata .= "<p class='price'>" . $vo['flight_no'] . " | " . $vo['plane_model'] . "</p>";
            $evaldata .= "<p class='price'>交易号：<span class='flight-text-a5'>" . $vo['sequence_no'] . "</span></p>";
            $evaldata .= "<p class='price'>舱位码：<span class='flight-text-a5'>" . $vo['seat_class'] . " 舱</span></p>";
            $evaldata .= "<p class='price'>起降机场：<span class='flight-text-a5'>" . $vo['start_code'] . "" . $vo['dep_code'] . " " . $vo['org_jetquay'] . " - " . $vo['end_code'] . $vo['arr_code'] . " " . $vo['dst_jetquay'] . "</span></p>";
            $evaldata .= "<p class='price'>起降时间：<span class='flight-text-a5'>" . $vo['dep_date'] . " " . $vo['dep_time'] . " -- " . $vo['dep_date'] . " " . $vo['arr_time'] . "</span></p>";
            $evaldata .= "<p class='price'>乘机人：<span class='flight-text-a5'>" . $vo['passenger_name'] . "</span></p>";
            $evaldata .= "<p class='price'>订单时间：<span class='flight-text-a5'>" . $vo['create_time'] . "</span><i class='icon-flight'></i></p>";
            $evaldata .= "<p class='price'>订单金额：<dfn>&yen; " . $vo['price_total'] . "$refund</dfn></p>";
            $evaldata .= "<p class='price'>订单状态：<span style='color:#f08519'>$orderState</span></p>";
            $evaldata .= "</li>";
            $evaldata .= "</ul>";
        }
        return $evaldata;
    }

    /**
     * [planeTicketDetail 我的机票 查看详情]
     */
    public function planeTicketDetail() {
        $M = M();
        $state = Top::FlightOrderStateSubmitted;

        $id = I('get.id');

        $list = $M->table('top_visitor_order_flight_detail as d')
                ->where("d.order_flight_id = '{$id}'")
                ->field(array(
                    'd.id' => 'id',
                    'd.pay_time' => 'pay_time',
                    'd.flight_no' => 'flight_no',
                    'd.sequence_no' => 'sequence_no',
                    'd.dep_code' => 'dep_code',
                    'd.arr_code' => 'arr_code',
                    'd.dep_date' => 'dep_date',
                    'd.dep_time' => 'dep_time',
                    'd.arr_time' => 'arr_time',
                    'd.plane_model' => 'plane_model',
                    'd.passenger_name' => 'passenger_name',
                    'd.passenger_type' => 'passenger_type',
                    'd.settle_price' => 'settle_price',
                    'd.par_price' => 'par_price',
                    'd.fuel_tax' => 'fuel_tax',
                    'd.airport_tax' => 'airport_tax',
                    'd.state' => 'state',
                    'd.ticket_no' => 'ticket_no',
                    'd.create_time' => 'create_time',
                ))
                ->order('d.id desc')
                ->select();

        $this->assign('list', $list);

        foreach ($list as $key => $vo) {

            if ($vo['state'] == 1) {
                $state = '已提交,未付款';
            } else if ($vo['state'] == 2) {
                $state = '已付款,待出票';
            } else if ($vo['state'] == 3) {
                $successTime = $vo['pay_time'];
                $state = '已出票&nbsp;&nbsp;&nbsp;' . $successTime;
            } else if ($vo['state'] == 6) {
                $state = '出票失败';
            } else if ($vo['state'] == 4) {
                $state = '已取消';
            } else if ($vo['state'] == 7) {
                $state = '预定失败';
            } else if ($vo['state'] == 5) {
                $state = '已退票,退票成功';
            } else if ($vo['state'] == 8) {
                $state = '退票失败';
            } else if ($vo['state'] == 9) {
                $state = '退票中,待退款';
            }

            if ($vo['passenger_type'] == 1) {
                $vo['passenger_type'] = '儿童';
            } else {
                $vo['passenger_type'] = '成人';
            }

            $vo['price_total'] = $vo['par_price'] + $vo['fuel_tax'] + $vo['airport_tax'];
            $price_total = $vo['par_price'] + $vo['fuel_tax'] + $vo['airport_tax'];
            $this->assign('price_total', $price_total);

            if ($vo['org_jetquay'] == '--' || $vo['org_jetquay'] == 'Array') {
                $vo['org_jetquay'] = '';
            }

            if ($vo['dst_jetquay'] == '--' || $vo['dst_jetquay'] == 'Array') {
                $vo['dst_jetquay'] = '';
            }

            $vo['flight_no'] = $this->nameToAirLine(substr($vo['flight_no'], 0, 2)) . " " . $vo['flight_no'];
            $flightNo = $this->nameToAirLine(substr($vo['flight_no'], 0, 2)) . " " . $vo['flight_no'];
            $this->assign('flightNo', $flightNo);

            $vo['start_code'] = $this->nameToAirport($vo['dep_code']);
            $vo['end_code'] = $this->nameToAirport($vo['arr_code']);

            $vo['org'] = $vo['dep_code'];
            $vo['dst'] = $vo['arr_code'];

            $vo['dep_code'] = $this->nameToFullAirport($vo['dep_code']);
            $vo['arr_code'] = $this->nameToFullAirport($vo['arr_code']);
            $vo['price_total'] = Utils::getYuan($vo['price_total']);

            $vo['ticket_no'] = rtrim($vo['ticket_no'], ",");
            $vo['ticket_no'] = str_replace(",", " ", $vo['ticket_no']);

            $vo['dep_time'] = substr($vo['dep_time'], 0, 2) . ':' . substr($vo['dep_time'], 2, 2);
            $vo['arr_time'] = substr($vo['arr_time'], 0, 2) . ':' . substr($vo['arr_time'], 2, 2);

            $vo['detail'] = "(结算价" . Utils::getYuan($vo['par_price']) . "+燃油税" . Utils::getYuan($vo['fuel_tax']) . "+基建费" . Utils::getYuan($vo['airport_tax']) . ")";
            $detail = "(结算价" . Utils::getYuan($vo['par_price']) . "+燃油税" . Utils::getYuan($vo['fuel_tax']) . "+基建费" . Utils::getYuan($vo['airport_tax']) . ")";
            $this->assign('detail', $detail);

            $ticketState = Top::FlightOrderStateTicked;

            $nowTime = date("YmdHis", time());
            $vo['flightDate'] = $vo['dep_date'] . " " . $vo['dep_time'] . ":00";


            $flightTime = date('YmdHis', strtotime('+1 hour', strtotime($vo['flightDate'])));

            if ($vo['state'] == $ticketState && $nowTime - $flightTime < 0) {
                $refund = "<a href=" . U('WxJsAPI/refundApplication', array('ticket_no' => $vo['ticket_no'], 'sequence_no' => $vo['sequence_no'])) . ">
                    <input type='button' class='btn btn-warning' style='float:right' value='申请退票'>
                    </a>";
            } else {
                $refund = '';
            }


            $evaldata .= "<ul class='tradeList' style='height:100%'>";
            $evaldata .= "<li>";
            $evaldata .= "<p class='price'>乘机人：<span class='flight-text-a5'>" . $vo['passenger_name'] . "</span></p>";
            $evaldata .= "<p class='price'>票号：<span class='flight-text-a5'>" . $vo['ticket_no'] . "</span></p>";
            $evaldata .= "<p class='price'>乘客类型：<span class='flight-text-a5'>" . $vo['passenger_type'] . "</span>";
            //$evaldata .= "<p class='price'>机票状态：<dfn>" . $state . "</dfn><i class='icon-flight'></i>";
            $evaldata .= $refund;
            $evaldata .= "</p>";
            $evaldata .= "</li>";
            $evaldata .= "</ul>";
        }

        $depDate = $list[0]['dep_date'] . " " . substr($list[0]['dep_time'], 0, 2) . ':' . substr($list[0]['dep_time'], 2, 2) . ":00";
        $date = date("Y-m-d H:i:s", time());
        $this->assign('date', $date);
        $this->assign('depDate', $depDate);
        $this->assign('id', $id);
        $this->assign('html', $evaldata);
        $this->display();
    }

    /**
     * 订单取消
     */
    public function orderCancel() {
        if (IS_POST && IS_AJAX) {
            $url = $this->orderCancelUrl();
            $data['agencyCode'] = $this->agencyCode();
            $data['orderNo'] = I('sequence_no');    //指平台订单号 (liantuoOrderNo)
            $data['canclePNR'] = 1;                     //1同时取消PNR;0不取消PNR;
            $sign = $this->agencyCode() . $data['canclePNR'] . $data['orderNo'] . $this->sign();
            $data['sign'] = strtolower(md5($sign));

            //返回 xml 格式
            $result = Utils::vpost($url, $data);
            //转换成数组
            $listAllData = $this->xml_to_array($result);
            $returnCode = $listAllData['returnCode'][0];

            if ($returnCode == 'S') {
                $state['state'] = Top::FlightOrderStateCanceled;
                $flightResult = M('visitor_order_flight')->where("sequence_no =" . $data['orderNo'])->save($state);
                $detailRestult = M('visitor_order_flight_detail')->where("sequence_no =" . $data['orderNo'])->save($state);

                if ($flightResult && $detailRestult) {
                    $data['status'] = 1;
                    $data['msg'] = '取消成功';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 0;
                $data['msg'] = $listAllData['returnMessage'][0];
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 删除订单
     */
    public function deleteOrder() {
        $id = I('get.id');
        $data['state'] = Top::FlightOrderStateDeleted;

        M('visitor_order_flight_detail')->where("order_flight_id = '{$id}'")->save($data);
        M('visitor_order_flight')->where("id = '{$id}'")->save($data);
        $this->redirect("WxJsAPI/myPlaneTicket");
    }

    /**
     * 三字码
     */
    public function airportname($code) {
        $codeArr = array(
            "阿克苏" => "AKU",
            '阿尔山' => 'YIE',
            '阿里' => 'NGQ',
            '安顺' => 'AVA',
            "阿勒泰" => "AAT",
            "安康" => "AKA",
            "安庆" => "AQG",
            "安阳" => "AYN",
            "鞍山" => "AOG",
            "百色" => "AEB",
            "保山" => "BSD",
            '毕节' => 'BFJ',
            "包头" => "BAV",
            "蚌埠" => "BFU",
            "北海" => "BHY",
            "北京" => "PEK",
            //"北京南苑" => "NAY",
            "博乐" => "BPL",
            "长春" => "CGQ",
            "常德" => "CGD",
            "昌都" => "BPX",
            "长沙" => "CSX",
            '长海' => 'CNI',
            "长治" => "CIH",
            "常州" => "CZX",
            "朝阳" => "CHG",
            "成都" => "CTU",
            "赤峰" => "CIF",
            '酒泉' => 'CHW',
            "重庆" => "CKG",
            "长白山" => "NBS",
            "大连" => "DLC",
            "大理" => "DLU",
            "丹东" => "DDG",
            "大同" => "DAT",
            '迪庆' => 'DIG',
            '稻城' => 'DCY',
            "达县" => "DAX",
            "香格里拉" => "DIG",
            "东营" => "DOY",
            '达州' => 'DAX',
            "敦煌" => "DNH",
            "大庆" => "DQA",
            "芒市" => "LUM",
            "鄂尔多斯" => "DSN",
            "恩施" => "ENH",
            '延安' => 'ENY',
            "二连浩特" => "ERL",
            "佛山" => "FUO",
            '富蕴' => 'FYN',
            "福州" => "FOC",
            "阜阳" => "FUG",
            "赣州" => "KOW",
            "格尔木" => "GOQ",
            "广元" => "GYS",
            "广州" => "CAN",
            "桂林" => "KWL",
            "贵阳" => "KWE",
            '广汉' => 'GHN',
            "固原" => "GYU",
            '甘南' => 'GXH',
            "海口" => "HAK",
            "海拉尔" => "HLD",
            "哈密" => "HMI",
            "邯郸" => "HDG",
            '韶关' => 'HSC',
            "杭州" => "HGH",
            '怀化' => 'HJJ',
            "汉中" => "HZG",
            "哈尔滨" => "HRB",
            "合肥" => "HFE",
            "黑河" => "HEK",
            '花莲' => 'HUN',
            '衡阳' => 'HNY',
            '惠州' => 'HUZ',
            "和田" => "HTN",
            "呼和浩特" => "HET",
            "黄山" => "TXN",
            "台州" => "HYN",
            "芷江" => "HJJ",
            '神农架' => 'HPG',
            "淮安" => "HIA",
            "九寨沟" => "JZH",
            "佳木斯" => "JMU",
            "嘉峪关" => "JGN",
            "济南" => "TNA",
            "景德镇" => "JDZ",
            "井冈山" => "JGS",
            "济宁" => "JNG",
            "锦州" => "JNZ",
            "九江" => "JIU",
            "鸡西" => "JXA",
            "泉州" => "JJN",
            '吉林' => 'JIL',
            "西双版纳" => "JHG",
            "布尔津" => "KJI",
            "克拉玛依" => "KRY",
            '高雄' => 'KHH',
            "喀什" => "KHG",
            "库尔勒" => "KRL",
            "库车" => "KCA",
            "昆明" => "KMG",
            '金门' => 'KNH',
            "康定" => "KGT",
            "兰州" => "LHW",
            "拉萨" => "LXA",
            "连云港" => "LYG",
            "丽江" => "LJG",
            "临沧" => "LNJ",
            '连城' => 'LCX',
            "临沂" => "LYI",
            "林芝" => "LZY",
            "黎平" => "HZH",
            "柳州" => "LZH",
            "洛阳" => "LYA",
            "泸州" => "LZO",
            "龙岩" => "LCX",
            "荔波" => "LLB",
            "满洲里" => "NZH",
            "梅州" => "MXZ",
            "绵阳" => "MIG",
            "牡丹江" => "MDG",
            '马公' => 'MZG',
            "漠河" => "OHE",
            "南昌" => "KHN",
            "南充" => "NAO",
            "南京" => "NKG",
            '宁蒗' => 'NLH',
            "南宁" => "NNG",
            "南通" => "NTG",
            "南阳" => "NNY",
            "宁波" => "NGB",
            "那拉提" => "NLT",
            "攀枝花" => "PZI",
            "且末" => "IQM",
            "青岛" => "TAO",
            "庆阳" => "IQN",
            "山海关" => "SHP",
            "齐齐哈尔" => "NDG",
            "衢州" => "JUZ",
            "黔江" => "JIQ",
            '池州' => 'JUH',
            '金昌' => 'JIC',
            '台中' => 'RMQ',
            '巴彦淖尔' => 'RLK',
            '日喀则' => 'RKZ',
            "三亚" => "SYX",
            "上海" => "SHA",
            //"上海浦东" => "PVG",
            "汕头" => "SWA",
            "沈阳" => "SHE",
            '秦皇岛' => 'SHP',
            '普洱' => 'SYM',
            "深圳" => "SZX",
            '荆州' => 'SHS',
            "石家庄" => "SJW",
            "思茅" => "SYM",
            "塔城" => "TCG",
            "唐山" => "TVS",
            "太原" => "TYN",
            "天津" => "TSN",
            '台东' => 'TTT',
            '吐鲁番' => 'TLQ',
            '台南' => 'TNN',
            '通化' => 'TNH',
            "通辽" => "TGO",
            "铜仁" => "TEN",
            "腾冲" => "TCZ",
            "天水" => "THQ",
            "乌兰浩特" => "HLH",
            "乌鲁木齐" => "URC",
            "万州" => "WXN",
            "潍坊" => "WEF",
            "威海" => "WEH",
            "文山" => "WNH",
            "温州" => "WNZ",
            "乌海" => "WUA",
            "武汉" => "WUH",
            "无锡" => "WUX",
            '望安' => 'WOT',
            "武夷山" => "WUS",
            "梧州" => "WUZ",
            "厦门" => "XMN",
            "襄阳" => "XFN",
            "西安" => "XIY",
            '邢台' => 'XNT',
            '新源' => 'NLT',
            "西昌" => "XIC",
            "锡林浩特" => "XIL",
            "西宁" => "XNN",
            "徐州" => "XUZ",
            "兴义" => "ACX",
            "延安" => "ENY",
            "盐城" => "YNZ",
            "延吉" => "YNJ",
            "烟台" => "YNT",
            "宜宾" => "YBP",
            "宜昌" => "YIH",
            "银川" => "INC",
            "伊宁" => "YIN",
            "义乌" => "YIW",
            "永州" => "LLF",
            "榆林" => "UYN",
            "运城" => "YCU",
            "伊春" => "LDS",
            "玉树" => "YUS",
            '张掖' => 'YZY',
            "扬州" => "YTY",
            '宜春' => 'YIC',
            "张家界" => "DYG",
            "湛江" => "ZHA",
            "昭通" => "ZAT",
            "郑州" => "CGO",
            "舟山" => "HSN",
            "珠海" => "ZUH",
            "中卫" => "ZHY",
            "遵义" => "ZYI",
            '张家口' => 'ZQZ',
        );
        return $codeArr[$code];
    }

    //三字码
    function nameToAirport($code) {
        $codearr = array(
            'AKU' => '阿克苏',
            'AAT' => '阿勒泰',
            'AKA' => '安康',
            'AVA' => '安顺',
            'AQG' => '安庆',
            'AYN' => '安阳',
            'AOG' => '鞍山',
            'AEB' => '百色',
            'BSD' => '保山',
            'BFJ' => '毕节',
            'BFU' => '蚌埠',
            'BAV' => '包头',
            'BHY' => '北海',
            'PEK' => '北京',
            //'NAY' => '北京南苑',
            'BPL' => '博乐',
            'CGQ' => '长春',
            'CGD' => '常德',
            'CNI' => '长海',
            'BPX' => '昌都',
            'CSX' => '长沙',
            'CIH' => '长治',
            'CZX' => '常州',
            'CHW' => '酒泉',
            'CHG' => '朝阳',
            'CTU' => '成都',
            'CIF' => '赤峰',
            'CKG' => '重庆',
            'NBS' => '长白山',
            'DLC' => '大连',
            'DAX' => '达州',
            'DLU' => '大理',
            'DDG' => '丹东',
            'DAT' => '大同',
            'DAX' => '达县',
            'DCY' => '稻城',
            'DIG' => '迪庆',
            'DOY' => '东营',
            'DNH' => '敦煌',
            'DQA' => '大庆',
            'LUM' => '德宏',
            'DSN' => '鄂尔多斯',
            'ENH' => '恩施',
            'ENY' => '延安',
            'ERL' => '二连浩特',
            'FUO' => '佛山',
            'FOC' => '福州',
            'FYN' => '富蕴',
            'FUG' => '阜阳',
            'KOW' => '赣州',
            'GOQ' => '格尔木',
            'GHN' => '广汉',
            'GXH' => '甘南',
            'GYS' => '广元',
            'CAN' => '广州',
            'KWL' => '桂林',
            'KWE' => '贵阳',
            'GYU' => '固原',
            'HAK' => '海口',
            'HLD' => '海拉尔',
            'HMI' => '哈密',
            'HDG' => '邯郸',
            'HPG' => '神农架',
            'HSC' => '韶关',
            'HUZ' => '惠州',
            'HGH' => '杭州',
            'HZG' => '汉中',
            'HRB' => '哈尔滨',
            'HFE' => '合肥',
            'HEK' => '黑河',
            'HNY' => '衡阳',
            'HUN' => '花莲',
            'HTN' => '和田',
            'HET' => '呼和浩特',
            'TXN' => '黄山',
            'HYN' => '黄岩',
            'HJJ' => '怀化',
            'HIA' => '淮安',
            'JIL' => '吉林',
            'JZH' => '黄龙',
            'JMU' => '佳木斯',
            'JGN' => '嘉峪关',
            'TNA' => '济南',
            'JDZ' => '景德镇',
            'JGS' => '井冈山',
            'JNG' => '济宁',
            'JNZ' => '锦州',
            'JIU' => '九江',
            'JIC' => '金昌',
            'JUH' => '池州',
            'JZH' => '九寨沟',
            'JXA' => '鸡西',
            'JJN' => '晋江',
            'JHG' => '景洪',
            'KRY' => '克拉玛依',
            'KHG' => '喀什',
            'KRL' => '库尔勒',
            'KCA' => '库车',
            'KJI' => '布尔津',
            'KMG' => '昆明',
            'KHH' => '高雄',
            'KGT' => '康定',
            'LHW' => '兰州',
            'LXA' => '拉萨',
            'LYG' => '连云港',
            'LJG' => '丽江',
            'LCX' => '连城',
            'LNJ' => '临沧',
            'LYI' => '临沂',
            'LZY' => '林芝',
            'HZH' => '黎平',
            'LZH' => '柳州',
            'LYA' => '洛阳',
            'LZO' => '泸州',
            'LLB' => '荔波',
            'LCX' => '龙岩',
            'LUM' => '芒市',
            'NZH' => '满洲里',
            'MZG' => '马公',
            'MXZ' => '梅州',
            'MIG' => '绵阳',
            'MDG' => '牡丹江',
            'OHE' => '漠河',
            'KHN' => '南昌',
            'KNH' => '金门',
            'NAO' => '南充',
            'NKG' => '南京',
            'NLH' => '宁蒗',
            'NGQ' => '阿里',
            'NNG' => '南宁',
            'NTG' => '南通',
            'NNY' => '南阳',
            'NGB' => '宁波',
            'NLT' => '那拉提',
            'PZI' => '攀枝花',
            'IQM' => '且末',
            'TAO' => '青岛',
            'IQN' => '庆阳',
            'SHP' => '秦皇岛',
            'NDG' => '齐齐哈尔',
            'JJN' => '泉州',
            'JUZ' => '衢州',
            'JIQ' => '黔江',
            'RMQ' => '台中',
            'RLK' => '巴彦淖尔',
            'RKZ' => '日喀则',
            'SYX' => '三亚',
            'SHA' => '上海',
            //'PVG' => '上海浦东',
            'SWA' => '汕头',
            'SHS' => '荆州',
            'SHE' => '沈阳',
            'SYM' => '普洱',
            'SZX' => '深圳',
            'SJW' => '石家庄',
            'SYM' => '思茅',
            'SHP' => '山海关',
            'TCG' => '塔城',
            'TNH' => '通化',
            'TVS' => '唐山',
            'TYN' => '太原',
            'TSN' => '天津',
            'TGO' => '通辽',
            'TEN' => '铜仁',
            'TLQ' => '吐鲁番',
            'TCZ' => '腾冲',
            'TTT' => '台东',
            'TNN' => '台南',
            'THQ' => '天水',
            'HYN' => '台州',
            'HLH' => '乌兰浩特',
            'URC' => '乌鲁木齐',
            'WXN' => '万州',
            'WEF' => '潍坊',
            'WEH' => '威海',
            'WNH' => '文山',
            'WNZ' => '温州',
            'WUA' => '乌海',
            'WUH' => '武汉',
            'WUX' => '无锡',
            'WUS' => '武夷山',
            'WUZ' => '梧州',
            'WOT' => '望安',
            'XMN' => '厦门',
            'XFN' => '襄阳',
            'NLT' => '新源',
            'XIY' => '西安',
            'XIC' => '西昌',
            'XNT' => '邢台',
            'XIL' => '锡林浩特',
            'XNN' => '西宁',
            'JHG' => '西双版纳',
            'XUZ' => '徐州',
            'ACX' => '兴义',
            'DIG' => '香格里拉',
            'ENY' => '延安',
            'YNZ' => '盐城',
            'YNJ' => '延吉',
            'YNT' => '烟台',
            'YBP' => '宜宾',
            'YIH' => '宜昌',
            'YIE' => '阿尔山',
            'INC' => '银川',
            'YIN' => '伊宁',
            'YIW' => '义乌',
            'LLF' => '永州',
            'UYN' => '榆林',
            'YCU' => '运城',
            'LDS' => '伊春',
            'YUS' => '玉树',
            'YTY' => '扬州',
            'YZY' => '张掖',
            'YIC' => '宜春',
            'DYG' => '张家界',
            'ZHA' => '湛江',
            'ZAT' => '昭通',
            'CGO' => '郑州',
            'HSN' => '舟山',
            'ZUH' => '珠海',
            'ZHY' => '中卫',
            'HJJ' => '芷江',
            'ZYI' => '遵义',
            'ZQZ' => '张家口',
        );
        return $codearr[$code];
    }

    //二字码
    function nameToAirLine($code) {
        $codearr = array(
            'CA' => '中国国际航空公司',
            'CZ' => '中国南方航空公司',
            'MU' => '中国东方航空公司',
            'MF' => '中国厦门航空公司',
            '3U' => '中国四川航空公司',
            'CN' => '大新华航空有限公司',
            'G5' => '华夏航空有限公司',
            'HO' => '上海吉祥航空有限公司',
            'HU' => '海南航空公司',
            'SC' => '中国山东航空公司',
            'ZH' => '中国深圳航空公司',
            'FM' => '上海航空公司',
            'BK' => '奥凯航空有限公司',
            'EU' => '鹰联航空有限公司',
            'GS' => '天津航空有限公司',
            'KN' => '中国联合航空有限公司',
            'JD' => '首都航空',
            'IV' => '中国福建航空公司',
            'CJ' => '中国北方航空公司',
            '8C' => '东星航空有限公司',
            '8L' => '云南祥鹏航空有限责任公司',
            'OQ' => '重庆航空有限责任公司',
            'VD' => '鲲鹏航空有限公司',
            'JR' => '中国幸福航空',
            'NS' => '东北航空有限公司',
            'PN' => '西部航空有限责任公司',
            '9C' => '春秋航空公司',
            'HR' => '中国联合航空公司',
            'IJ' => '长城航空有限公司',
            'F4' => '上海国际货运航空有限公司',
            'JI' => '翡翠国际货运航空有限责任公司',
            'J5' => '东海航空有限公司',
            'PO' => '中国邮政航空有限公司',
            'LD' => '香港华民航空',
            'PN' => '西部航空有限责任公司',
            'HC' => '中国海洋直升机公司',
            'HY' => '中国航空货运公司',
            'Y8' => '扬子江快运航空有限公司',
            'NX' => '澳门航空公司',
            'ZG' => '非凡航空',
            'CX' => '国泰航空有限公司',
            'HX' => '香港航空公司',
            'O8' => '甘泉香港航空公司',
            'UO' => '香港快运航空',
            'CI' => '中华航空股份有限公司',
            'BR' => '长荣航空股份有限公司',
            'GE' => '复兴航空运输股份有限公司',
            'AE' => '华信航空股份有限公司',
            'B7' => '立荣航空公司EU鹰联航空',
            'EF' => '远东航空股份有限公司',
        );
        return $codearr[$code];
    }

//三字码
    function nameToFullAirport($code) {
        $codearr = array(
            'AVA' => '黄果树机场',
            'AYN' => '北郊机场',
            'AKU' => '阿克苏机场',
            'AAT' => '阿勒泰机场',
            'AKA' => '安康机场',
            'AQG' => '安庆机场',
            'AOG' => '鞍山机场',
            'AEB' => '巴马机场',
            'BSD' => '云瑞机场',
            'BFU' => '蚌埠机场',
            'BDU' => '昌都邦达',
            'BAV' => '二里半机场',
            'BFJ' => '飞雄机场',
            'BHY' => '福城机场',
            'PEK' => '首都机场',
            'NAY' => '南苑机场',
            'BPL' => '博乐阿拉山口机场',
            'CGQ' => '龙嘉国际机场',
            'CHW' => '酒泉机场',
            'CYI' => '嘉义机场',
            'CGD' => '桃花源机场',
            'CMJ' => '七美机场',
            'BPX' => '邦达机场',
            'CSX' => '黄花机场',
            'CIH' => '王村机场',
            'CZX' => '奔牛机场',
            'CNI' => '长海机场',
            'CHG' => '朝阳机场',
            'CTU' => '双流机场',
            'CIF' => '玉龙机场',
            'CKG' => '江北机场',
            'NBS' => '长白山机场',
            'DLC' => '国际机场',
            'DCY' => '亚丁机场',
            'DLU' => '荒草坝机场',
            'DDG' => '浪头机场',
            'DAT' => '大同机场',
            'DAX' => '达州机场',
            'DIG' => '香格里拉机场',
            'DOY' => '胜利机场',
            'DNH' => '敦煌机场',
            'DQA' => '萨尔图机场',
            'LUM' => '芒市机场',
            'DSN' => '伊金霍洛机场',
            'ENH' => '恩施机场',
            'ENY' => '二十里铺机场',
            'ERL' => '赛乌苏国际机场',
            'FUO' => '沙堤机场',
            'FYN' => '富蕴机场',
            'FOC' => '长乐机场',
            'FUG' => '西关机场',
            'JIL' => '二台子机场',
            'KOW' => '黄金机场',
            'GOQ' => '格尔木机场',
            'GYS' => '盘龙机场',
            'GXH' => '夏河机场',
            'GHN' => '广汉机场',
            'CAN' => '白云机场',
            'KWL' => '两江机场',
            'KWE' => '龙洞堡机场',
            'KHH' => '高雄机场',
            'GYU' => '六盘山机场',
            'HAK' => '美兰机场',
            'HLD' => '东山机场',
            'HMI' => '哈密机场',
            'HDG' => '邯郸机场',
            'HSC' => '韶关机场',
            'HGH' => '萧山机场',
            'HZG' => '西关机场',
            'HRB' => '太平机场',
            'HFE' => '骆岗机场',
            'HEK' => '黑河机场',
            'HTN' => '和田机场',
            'HPG' => '红坪机场',
            'HET' => '白塔国际机场',
            'TXN' => '屯溪机场',
            'HYN' => '路桥机场',
            'HUZ' => '平潭机场',
            'HJJ' => '芷江机场',
            'HIA' => '涟水机场',
            'HNY' => '东江机场',
            'JMU' => '佳木斯机场',
            'JGN' => '嘉峪关机场',
            'TNA' => '遥墙机场',
            'JDZ' => '罗家机场',
            'JGS' => '井冈山机场',
            'JNG' => '济宁机场',
            'JUH' => '九华山机场',
            'JNZ' => '小岭子机场',
            'JIU' => '庐山机场',
            'JIC' => '金昌机场',
            'JZH' => '黄龙机场',
            'JXA' => '兴凯湖机场',
            'JJN' => '晋江机场',
            'KJI' => '喀纳斯机场',
            'KRY' => '克拉玛依机场',
            'KHG' => '喀什机场',
            'KRL' => '库尔勒机场',
            'KCA' => '库车机场',
            'KMG' => '巫家坝机场',
            'KNH' => '尚义机场',
            'KGT' => '康定机场',
            'KNC' => '吉安机场',
            'LHW' => '兰州机场',
            'LXA' => '贡嘎机场',
            'LCX' => '连城机场',
            'LYG' => '白塔埠机场',
            'LJG' => '三义机场',
            'LZJ' => '云南丽江机场',
            'LNJ' => '临沧机场',
            'LYI' => '沭埠岭机场',
            'LZY' => '米林机场',
            'HZH' => '黎平机场',
            'LZH' => '白莲机场',
            'LYA' => '洛阳机场',
            'LZO' => '蓝田机场',
            'LCX' => '福建龙岩冠豸山机场',
            'LLB' => '荔波机场',
            'LUM' => '芒市机场',
            'NZH' => '西郊机场',
            'MXZ' => '梅州机场',
            'MZG' => '马公机场',
            'MIG' => '南郊机场',
            'MDG' => '海浪机场',
            'OHE' => '古莲机场',
            'KHN' => '昌北机场',
            'NAO' => '高坪机场',
            'NGQ' => '昆莎机场',
            'NKG' => '禄口机场',
            'NNG' => '吴圩机场',
            'NTG' => '兴东机场',
            'NLH' => '泸沽湖机场',
            'NNY' => '姜营机场',
            'NGB' => '栎社机场',
            'NNN' => '嫩江机场',
            'NLT' => '那拉提机场',
            'PZI' => '保安营机场',
            'IQM' => '且末机场',
            'TAO' => '流亭机场',
            'IQN' => '庆阳机场',
            'NDG' => '三家子机场',
            'JJN' => '泉州晋江国际机场',
            'JUZ' => '衢州机场',
            'JIQ' => '武陵山机场',
            'RMQ' => '清泉岗机场',
            'RKZ' => '和平机场',
            'RLK' => '天吉泰机场',
            'SZV' => '苏州机场',
            'SYX' => '凤凰机场',
            'SHA' => '虹桥机场',
            'PVG' => '浦东机场',
            'SWA' => '揭阳潮汕机场',
            'SHE' => '桃仙机场',
            'SZX' => '宝安机场',
            'SJW' => '正定机场',
            'SYM' => '普洱机场',
            'SHS' => '沙市机场',
            'SHP' => '山海关机场',
            'SWA' => '外砂机场',
            'TNH' => '通化机场',
            'TCG' => '塔城机场',
            'TVS' => '三女河机场',
            'TTT' => '丰年机场',
            'TLQ' => '交河机场',
            'TYN' => '武宿机场',
            'TVS' => '三女河机场',
            'TSN' => '滨海机场',
            'TSA' => '台北松山机场',
            'TPE' => '桃园机场',
            'TGO' => '通辽机场',
            'TEN' => '凤凰机场',
            'TCZ' => '驼峰机场',
            'THQ' => '麦积山机场',
            'TNN' => '台南机场',
            'HYN' => '台州路桥机场',
            'HUN' => '花莲机场',
            'HLH' => '乌兰浩特机场',
            'URC' => '地窝堡机场',
            'WXN' => '五桥机场',
            'WEF' => '潍坊机场',
            'WEH' => '文登大水泊机场',
            'WOT' => '望安机场',
            'WNH' => '普者黑机场',
            'WNZ' => '永强机场',
            'WUA' => '乌海机场',
            'WUH' => '天河机场',
            'WJD' => '王家墩国际机场',
            'WUX' => '硕放机场',
            'WUS' => '武夷山机场',
            'WUZ' => '长洲岛机场',
            'XMN' => '高崎机场',
            'XFN' => '刘集机场',
            'XEN' => '兴城机场',
            'XIY' => '咸阳机场',
            'XIC' => '青山机场',
            'XIL' => '锡林浩特机场',
            'XNT' => '褡裢机场',
            'XNN' => '曹家堡机场',
            'NLT' => '那拉提机场',
            'JHG' => '嘎洒机场',
            'XUZ' => '观音机场',
            'ACX' => '兴义万峰林机场',
            'DIG' => '香格里拉机场',
            'ENY' => '二十里铺机场',
            'YNZ' => '南洋机场',
            'YNJ' => '朝阳川机场',
            'YIE' => '伊尔施机场',
            'YIC' => '明月山机场',
            'YNT' => '莱山机场',
            'YBP' => '宜宾机场',
            'YIH' => '三峡机场',
            'INC' => '河东机场',
            'YIN' => '伊宁机场',
            'YZY' => '张掖机场',
            'YIW' => '义乌机场',
            'LLF' => '零陵机场',
            'UYN' => '西沙机场',
            'YCU' => '关公机场',
            'LDS' => '林都机场',
            'YUS' => '巴塘机场',
            'YTY' => '泰州机场',
            'DYG' => '荷花机场',
            'ZHA' => '湛江机场',
            'ZAT' => '昭通机场',
            'CGO' => '新郑机场',
            'HSN' => '普陀山朱家尖机场',
            'ZUH' => '三灶机场',
            'ZHY' => '沙坡头机场',
            'ZYI' => '遵义机场',
            'ZQZ' => '宁远机场',
        );
        return $codearr[$code];
    }

}
